<?php


namespace Drupal\shushengyuan;


use Drupal\commerce_weight_shipping\Entity\CommerceWeightShipping;
use Drupal\distribution\Entity\Distribution;
use Drupal\s_commerce_service\Entity\SCommerceService;
use Drupal\s_commerce_service\Entity\SCommerceServiceLine;
use Drupal\shushengyuan\Schemas\ErrandItem;
use Drupal\shushengyuan\Schemas\File;
use Drupal\shushengyuan\Schemas\LineItemProduct;
use Drupal\shushengyuan\Schemas\Login;
use Drupal\shushengyuan\Schemas\OrderPayment;
use Drupal\shushengyuan\Schemas\PointExchangeOrder;
use Drupal\shushengyuan\Schemas\TopicItem;
use Drupal\shushengyuan\Schemas\User;
use Drupal\shushengyuan\Traits\ApiException;
use Drupal\shushengyuan\Traits\ServicesCommerceAddOrderTrait;
use Drupal\shushengyuan\Traits\ServicesControllerTrait;
use Drupal\shusy_card\Entity\ShusyCard;
use Drupal\shusy_cash\Entity\ShusyCash;
use Drupal\shusy_city\Entity\ShusyCity;
use Drupal\shusy_couponfree\Entity\ShusyCouponfree;
use Drupal\shusy_couponfree\Entity\ShusyCouponfreeLog;
use Drupal\shusy_distribution\Entity\ShusyDistribution;
use Drupal\shusy_errand\Entity\ShusyErrand;
use Drupal\shusy_errand\Entity\ShusyErrandOrder;
use Drupal\shusy_favorite_product\Entity\ShusyFavoriteProduct;
use Drupal\shusy_gift_card\Entity\ShusyGiftCard;
use Drupal\shusy_hot_topic\Entity\ShusyHotTopic;
use Drupal\shusy_hotel\Entity\ShusyHotel;
use Drupal\shusy_hotel\Entity\ShusyHotelLine;
use Drupal\shusy_hotel\Entity\ShusyHotelLineRoom;
use Drupal\shusy_hotel\Entity\ShusyHotelOrder;
use Drupal\shusy_hotel\Entity\ShusyHotelRoom;
use Drupal\shusy_maxms\Entity\ShusyMaxms;
use Drupal\shusy_pintuan\Entity\ShusyPintuan;
use Drupal\shusy_pintuan\Entity\ShusyPintuanPlayer;
use Drupal\shusy_plant_grass\Entity\ShusyPlantGrass;
use Drupal\shusy_plant_grass_comments\Entity\ShusyPlantGrassComments;
use Drupal\shusy_plant_grass_like\Entity\ShusyPlantGrassLike;
use Drupal\shusy_point_product\Entity\ShusyPointProduct;
use Drupal\shusy_point_product\Entity\ShusyPointProductOrder;
use Drupal\shusy_product\Entity\ShusyProductComment;
use Drupal\shusy_product\Entity\ShusyProductStandard;
use Drupal\shusy_product_in_store\Entity\ShusyProductInStore;
use Drupal\shusy_promote\Entity\ShusyPromote;
use Drupal\shusy_service\Entity\ShusyService;
use Drupal\shusy_sign\Entity\ShusySign;
use Drupal\shusy_store\Entity\ShusyStore;
use Drupal\shusy_taxation\Entity\ShusyTaxation;
use Drupal\shusy_store_coupon\Entity\ShusyStoreCoupon;
use Drupal\shusy_store_coupon\Entity\ShusyStoreCouponHold;
use Drupal\shusy_store_order\Entity\ShusyStoreOrder;
use Drupal\shusy_store_order_address\Entity\ShusyStoreOrderAddress;
use Drupal\shusy_store_order_line\Entity\ShusyStoreOrderLine;
use Drupal\shusy_store_order_line_product\Entity\ShusyStoreOrderLineProduct;
use Drupal\shusy_store_order_location\Entity\ShusyStoreOrderLocation;
use Drupal\shusy_store_order_note\Entity\ShusyStoreOrderNote;
use Drupal\shusy_store_order_pintuan\Entity\ShusyStoreOrderPintuan;
use Drupal\shusy_store_order_shipping\Entity\ShusyStoreOrderShipping;
use Drupal\shusy_sweepstake\Entity\ShusySweepstake;
use Drupal\shusy_sweepstake\Entity\ShusySweepstakeItem;
use Drupal\shusy_sweepstake\Entity\ShusySweepstakeLog;
use Drupal\shusy_sweepstake_bind_card\Entity\ShusySweepstakeBindCard;
use Drupal\shusy_sweepstake_bind_order\Entity\ShusySweepstakeBindOrder;
use Drupal\shusy_team\Entity\ShusyTeam;
use Drupal\shusy_team_apply\Entity\ShusyTeamApply;
use Drupal\shusy_team_company_apply\Entity\ShusyTeamCompanyApply;
use Drupal\shusy_topic\Entity\ShusyTopic;
use Drupal\shusy_vip\Entity\ShusyVip;
use Drupal\shusy_vip\Entity\ShusyVipBind;
use Drupal\ssystore\Entity\Ssystore;
use Drupal\swx_submsgs\Entity\SwxSubmsgs;
use Drupal\wx_mini_program\WxMiniProgramController;
use Drupal\wx_mini_qr\Entity\WxMiniQr;
use Drupal\wx_pay\WxPayMiniPayController;
use Drupal\youji_userwxinfo\Entity\YoujiUserwxinfo;
use EntityFieldQuery;
use EntityListWrapper;
use Exception;
use OpenApi\Annotations as OA;
use function Drupal\shushengyuan\Traits\trim;

class ShushengyuanServicesActionsController
{

    use ServicesControllerTrait;
    use ServicesCommerceAddOrderTrait;

    /**
     * @param string $code wx.login获取的code
     * @param string $uid 如果是转发 获取的uid
     * @param string $qr 如果是扫普通链接二维码 获取的二维码内容
     *                      https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html
     * @param string $scene 如果是扫小程序二维码 获取的二维码内容
     *                      https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
     *   主要使用接口B
     * @return array
     * 通过 code 换取 token 登录 并处理来源关系
     * @OA\Post(
     *    path="/common/login",
     *    summary="通过 code 换取 token 登录 并处理来源关系",
     *    tags={"v1.0","v2.0"},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required ={"code"},
     *        @OA\Property(
     *          property="code",
     *          type="string",
     *          description="wx.login获取的code",
     *        ),
     *        @OA\Property(
     *          property="uid",
     *          type="string",
     *          description="如果是转发 获取的uid",
     *          default=""
     *        ),
     *        @OA\Property(
     *          property="qr",
     *          type="string",
     *          default="",
     *          description="如果是扫普通链接二维码获取的二维码内容https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html",
     *        ),
     *        @OA\Property(
     *          property="scene",
     *          type="string",
     *          default="",
     *          description="如果是扫小程序二维码获取的二维码内容https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *        required ={"token"},
     *        @OA\Property(
     *          property="token",
     *          type="string",
     *          description="token",
     *        ),
     *        @OA\Property(property="user", ref="#/components/schemas/User"),
     *        @OA\Property(property="login", ref="#/components/schemas/Login",description="登录状态信息,是否显示商家入驻等控制信息均使用此传递",)
     *     )
     *   )
     * )
     * @deprecated
     * @see submitLogin
     */
    function login(string $code, string $uid = '', string $qr = '', string $scene = '')
    {
        watchdog(__FUNCTION__, serialize([$code, $uid, $qr, $scene]));
        $wxController = new WxMiniProgramController();
        $result = $wxController->login($code);
        if ($result['code'] == 0) {
            $pid = (int)$uid;
            if ($pid > 0) {
                $this->bind_parent($pid);
            }
            if (!empty($scene)) {
                $this->bind_parent_by_scene($scene);
            }
            if (!empty($qr)) {
                $this->bind_parent_by_qr($qr);
            }

            if (!empty($scene)) {
                if (module_exists('wx_mini_qr')) {
                    _wx_mini_qr_services_parse_scene($scene);
                }
            }

            return [
                'code' => (int)0,
                'msg' => (string)'ok',
                'token' => $result['token'],
                'user' => User::get($this->getUid()),
                'login' => Login::init($this->getUid(), FALSE, [$pid, $qr, $scene]),
            ];
        }
        return $result;
    }

    /**
     * @param string $code wx.login获取的code
     * @param array $options
     * @return array
     * 通过 code 换取 token 登录 并处理来源关系
     * @OA\Post(
     *    path="/common/submitLogin",
     *    summary="通过 code 换取 token 登录 并处理来源关系",
     *    tags={"v1.0"},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required ={"code"},
     *        @OA\Property(
     *          property="code",
     *          type="string",
     *          description="wx.login获取的code",
     *        ),
     *        @OA\Property(
     *          property="options",
     *          type="object",
     *          description="小程序onLoad query 参数",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="token",
     *         type="string",
     *         description="Token",
     *       ),
     *     )
     *   )
     * )
     */
    function submitLogin(string $code, array $options)
    {
        watchdog(__FUNCTION__, serialize([$code, $options]));
        $wxController = new WxMiniProgramController();
        $result = $wxController->login($code);
        if ($result['code'] == 0) {
            $url = FALSE;

            $pid = (int)($options['uid'] ?? 0);
            $qr = $options['q'] ?? '';
            $scene = $options['scene'] ?? '';
            if ($pid > 0) {
                $this->bind_parent($pid);
            }
            if (!empty($scene)) {
                $res = $this->bind_parent_by_scene($scene);
                if (isset($res['url'])) {
                    $url = $res['url'];
                }
            }
            if (!empty($qr)) {
                $this->bind_parent_by_qr($qr);
            }
            if (!empty($scene)) {
                if (module_exists('wx_mini_qr')) {
                    _wx_mini_qr_services_parse_scene($scene);
                }
            }
            //小程序分享
            if (isset($options['op'])) {
                switch ($options['op']) {
                    case 'product':
                        $product = $options['id'];
                        $type = 1;
                        $ptid = 0;
                        $url = "/pages/Goodsdetails/Goodsdetails?id={$product}&type={$type}&ptid={$ptid}";
                        break;
                    case 'pintuan':
                        $product = $options['id'];
                        $type = 3;
                        $ptid = $options['ptid'];
                        $url = "/pages/Goodsdetails/Goodsdetails?id={$product}&type={$type}&ptid={$ptid}";
                        break;
                }
            }
            return [
                'code' => (int)0,
                'msg' => (string)'ok',
                'token' => $result['token'],
                'user' => User::get($this->getUid()),
                'login' => Login::init($this->getUid(), FALSE, [$pid, $qr, $scene]),
                'url' => $url,
            ];
        }
        return $result;
    }

    /**
     * @param $pid
     * @return array
     * 绑定上家
     * uid 用户
     * pid 上家 如果分销关系无需申请 和 sid 一致 如果需要申请 则申请通过后才会记录 否则记录到pid->pid
     * tid 团队 如果存在团队的情况使用 此项目 则为可以发货的门店
     * sid 来源 初次绑定时使用 后面不会改变
     */
    protected function bind_parent($pid)
    {
        $uid = $this->getUid();
        $distribution = Distribution::getDistribution($uid);
        if (empty($distribution->id)) {
            $wSid = $pid;
            $wPid = $pid;

            $wTid = 0;
            $team = Distribution::getDistribution($pid);
            if ($team instanceof Distribution) {
                $wTid = $team->tid;
            }
            //检查是否是外部推广团长
            $es = shusy_distribution_load_multiple(FALSE, ['uid' => $pid]);
            if (!empty($es)) {
                $e = reset($es);
                if ($e instanceof ShusyDistribution) {
                    //状态 0 审核中 1 已通过 2 未通过
                    if ($e->status == 1) {
                        $wTid = $pid;
                    }
                }
            }

            //来源UID
            $distribution->sid = $wSid;
            $distribution->pid = $wPid;
            $distribution->tid = $wTid;
            $distribution->uid = $uid;
            $distribution->save();
        }
        //仅测试状态下可以通过分享形成团队推广关系
        if ($pid > 0 && $this->isDev()) {
            $this->bindTeam($pid);
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    protected function bindTeam(int $pid)
    {
        $uid = $this->getUid();
        //检查是否是团队推广人员
        $isTeam = shusy_team_apply_load_multiple(FALSE, [
            'uid' => $pid,
            'status' => 1,
        ]);
        if (!empty($isTeam) || $pid === 1) {
            $teams = shusy_team_load_multiple(FALSE, ['uid' => $uid]);
            if (empty($teams)) {
                $team = new ShusyTeam();
                $team->uid = $uid;
                $team->pid = $pid;
                $team->level = SHUSY_TEAM_LEVEL_MARKET_1;
                //申请之后才激活
                $team->status = 0;
                $team->save();
            }
        }
    }

    /**
     * @param $scene
     * @return array
     * 解析小程序二维码
     * 商品海报二维码
     * @see ProductItemInfo::getPoster
     * 分享码
     * @see ShushengyuanServicesRetrieveController::getShareQr
     * 团队推广码
     * @see ShushengyuanServicesRetrieveController::getTeamQrTeam
     * 扫码即申请快达人
     * @see ShushengyuanServicesRetrieveController::getErrandQr
     * @see ShushengyuanServicesRetrieveController::getTeamQrStore
     * @see ShushengyuanServicesRetrieveController::getStoreQr
     */
    protected function bind_parent_by_scene($scene)
    {
        $wxMiniQr = entity_load_single('wx_mini_qr', $scene);
        if ($wxMiniQr instanceof WxMiniQr) {
            $value = unserialize($wxMiniQr->value);
            if ($wxMiniQr->module == 'shushengyuan') {
                if (!empty(strstr($wxMiniQr->name, "share_qr_"))) {
                    [, $pid] = explode('share_qr_', $wxMiniQr->name);
                    return $this->bind_parent($pid);
                }
                if (!empty(strstr($wxMiniQr->name, "share_product_"))) {
                    $this->bind_parent($value['uid']);
                    $product = $value['product'];
                    //1 默认详情  2 秒杀详情 3去拼团 4 拼团详情
                    $type = 1;
                    if (isset($value['sType'])) {
                        $type = $value['sType'];
                    }
                    $ptid = 0;
                    $url = "/pages/Goodsdetails/Goodsdetails?id={$product}&type={$type}&ptid={$ptid}";
                    return ['code' => 0, 'msg' => 'ok', 'url' => $url];
                }
            }
            if ($wxMiniQr->module == 'shusy_team') {
                //成为内部成员必须扫码
                //扫统一申请码
                if ($value === 'teamApply') {
                    //归属默认
                    $this->bindTeam(1);
                    $url = "/pages/my/Teamapply/Teamapply";
                    return ['code' => 0, 'msg' => 'ok', 'url' => $url];
                }
                //扫成员推广码
                if (!empty(strstr($wxMiniQr->name, "teamApply_"))) {
                    [, $pid] = explode('teamApply_', $wxMiniQr->name);
                    $this->bindTeam($pid);
                    $this->bind_parent($pid);
                    $url = "/pages/my/Teamapply/Teamapply";
                    return ['code' => 0, 'msg' => 'ok', 'url' => $url];
                }
                //扫店铺推广码
                if (!empty(strstr($wxMiniQr->name, "storeApply_"))) {
                    [, $pid] = explode('storeApply_', $wxMiniQr->name);
                    $this->bind_parent($pid);
                    $url = "/pages/my/applyfor/applyfor?type=2";
                    return ['code' => 0, 'msg' => 'ok', 'url' => $url];
                }
            }

            //扫快达推广码
            if ($wxMiniQr->module == 'shusy_errand') {
                //扫统一申请码 独立建立快达团队
                if ($value == 'errandApply') {
                    $uid = $this->getUid();
                    $errands = shusy_errand_load_multiple(FALSE, ['uid' => $uid]);
                    if (!empty($errands)) {
                        $errand = reset($errands);
                    } else {
                        $errand = new ShusyErrand;
                        $errand->uid = $uid;
                    }
                    $errand->errand_id = 0;
                    $errand->is_admin = 1;
                    $errand->save();
                    $url = "/pages/errand/errandApply";
                    return ['code' => 0, 'msg' => 'ok', 'url' => $url];
                }
                //扫成员推广码
                if (!empty(strstr($wxMiniQr->name, "errandApply_"))) {
                    [, $pid] = explode('errandApply_', $wxMiniQr->name);
                    $this->bindErrand($pid);
                    $this->bind_parent($pid);
                    $url = "/pages/errand/errandApply";
                    return ['code' => 0, 'msg' => 'ok', 'url' => $url];
                }
            }

        }
        return ['code' => 1, 'msg' => '上家查找失败'];
    }

    /**
     * @param int $pid
     * 加入他人快达团队
     */
    protected function bindErrand(int $pid)
    {
        $pidErrands = shusy_errand_load_multiple(FALSE, ['uid' => $pid]);
        if (!empty($pidErrands)) {
            $pidErrand = reset($pidErrands);
            if ($pidErrand instanceof ShusyErrand) {
                $uid = $this->getUid();
                $errands = shusy_errand_load_multiple(FALSE, ['uid' => $uid]);
                if (empty($errands)) {
                    $errand = new ShusyErrand;
                    $errand->uid = $uid;
                    $errand->errand_id = $pidErrand->id;
                    $errand->is_admin = 0;
                    $errand->save();
                }
            }
        }
    }

    /**
     * @param $qr
     * @return array
     * 解析普通链接二维码
     */
    protected function bind_parent_by_qr($qr)
    {
        $code = '';
        if (!empty(strstr($qr, "wx_mini_qr%2Fqr%2F"))) {
            $urlCode = urldecode($qr);
            [, $code] = explode('wx_mini_qr/qr/', $urlCode);
        }
        if (!empty(strstr($qr, "wx_mini_qr/qr/"))) {
            [, $code] = explode('wx_mini_qr/qr/', $qr);
        }
        [$type, $pid] = explode(':', $code);
        if ($pid) {
            if ($type == 'share') {
                return $this->bind_parent($pid);
            }
        }
        return ['code' => 1, 'msg' => '上家查找失败'];
    }

    /**
     * @param string $iv 加密算法的初始向量
     * @param string $encrypted 加密数据
     * @return array
     * 用户授权，获取信息
     * @OA\Post(
     *    path="/common/set_user_info",
     *    summary="用户授权 common/set_user_info",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"iv","encrypted"},
     *        @OA\Property(
     *          property="iv",
     *          type="string",
     *          description="加密算法的初始向量",
     *        ),
     *        @OA\Property(
     *          property="encrypted",
     *          type="string",
     *          description="加密数据",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(property="user", ref="#/components/schemas/User")
     *     )
     *   )
     * )
     */
    function set_user_info(string $iv, string $encrypted)
    {
        try {
            $uid = $this->getUid();
            $mini = $this->mini;
            $sessionKey = wx_mini_program_get_session_key($uid);
            $decrypted = $mini->encryptor->decryptData($sessionKey, $iv, $encrypted);
            $nickName = $decrypted['nickName'];
            $sex = $decrypted['gender'];

            $es = entity_load('youji_userwxinfo', FALSE, ['uid' => $uid]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new YoujiUserwxinfo();
                $e->uid = $this->getUid();
            }
            if ($e instanceof YoujiUserwxinfo) {
                $e->avatar = $decrypted['avatarUrl'];
                $e->nickname = $nickName;
                $e->sex = $sex;
                $e->auth = 1;
                $e->save();
            }

            return [
                'code' => 0,
                'msg' => 'ok',
                'user' => User::get($uid),
            ];
        } catch (Exception $e) {
            watchdog_exception(__FUNCTION__, $e);
            return [
                'code' => 1,
                'msg' => '系统错误',
            ];
        }
    }

    /**
     * @param int $type
     * @param int $image
     * @param array $fids
     * @param string $title
     * @param string $content
     * @param array $topics
     * @param array $products
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EntityMetadataWrapperException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @OA\Post(
     *    path="/common/submit_plant_grass",
     *    summary="提交发布种草 common/submit_plant_grass",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"type","image","fids","title","content","topics",},
     *        @OA\Property(
     *          property="type",
     *          type="integer",
     *          description="类型 0 图文 1 视频",
     *        ),
     *        @OA\Property(
     *          property="image",
     *          type="integer",
     *          description="封面图 视频时才需要传 图文时默认取第一张",
     *        ),
     *        @OA\Property(
     *          property="fids",
     *          type="array",
     *          description="上传的图片/视频FID File.id",
     *          @OA\Items(type="integer"),
     *        ),
     *        @OA\Property(
     *          property="title",
     *          type="string",
     *          description="标题",
     *        ),
     *        @OA\Property(
     *          property="content",
     *          type="string",
     *          description="正文",
     *        ),
     *        @OA\Property(
     *          property="topics",
     *          type="array",
     *          description="话题IDS",
     *          @OA\Items(type="integer"),
     *        ),
     *        @OA\Property(
     *          property="products",
     *          type="array",
     *          description="关联商品IDS",
     *          @OA\Items(type="integer"),
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_plant_grass(int $type, $image, array $fids, string $title, string $content, array $topics, array $products = [])
    {
        $mini = $this->mini;

        $result = $mini->content_security->checkText($title);
        if ($result['errcode'] != 0) {
            return [
                'code' => 1,
                'msg' => '标题含有违法违规内容',
            ];
        }
        $result = $mini->content_security->checkText($content);
        if ($result['errcode'] != 0) {
            return [
                'code' => 1,
                'msg' => '内容含有违法违规内容',
            ];
        }

        //接入小程序内容鉴定接口
        $plant = new ShusyPlantGrass();
        $plant->title = $title;
        $plant->type = $type;
        $plant->content = $content;
        $plant->status = 0;
        $plantWrapper = $plant->wrapper();

        switch ($type) {
            case 0:
                $imgs = [];
                $field_name = 'field_images';
                $dir = $this->filePrepareDirectory($plant->entityType(), $field_name, $plant->bundle());
                foreach ($fids as $fid) {
                    $file = file_load($fid);
                    $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
                    $file = file_move($file, "{$dir}/{$fid}.{$ext}");
                    file_usage_add($file, $plant->entityType(), $plant->bundle(), $file->fid);
                    $imgs[] = ['fid' => $file->fid];
                }
                $plantWrapper->field_images->set($imgs);
                break;
            case 1:
                //视频时上传的封面
                $imgs = [];
                $field_name = 'field_images';
                $dir = $this->filePrepareDirectory($plant->entityType(), $field_name, $plant->bundle());
                if (!empty($image)) {
                    $file = file_load($image);
                    $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
                    $file = file_move($file, "{$dir}/{$image}.{$ext}");
                    file_usage_add($file, $plant->entityType(), $plant->bundle(), $file->fid);
                    $imgs[] = ['fid' => $file->fid];
                    $plantWrapper->field_images->set($imgs);
                }
                $imgs = [];
                $field_name = 'field_videos';
                $dir = $this->filePrepareDirectory($plant->entityType(), $field_name, $plant->bundle());
                foreach ($fids as $fid) {
                    $file = file_load($fid);
                    $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
                    $file = file_move($file, "{$dir}/{$fid}.{$ext}");
                    file_usage_add($file, $plant->entityType(), $plant->bundle(), $file->fid);
                    $imgs[] = [
                        'fid' => $file->fid,
                        'display' => 0,
                        'description' => '',
                    ];
                }
                $plantWrapper->field_videos->set($imgs);
                break;
        }

        if (!empty($topics)) {
            $plantWrapper->field_topics->set($topics);
        }
        if (!empty($products)) {
            $plantWrapper->field_products->set($products);
        }

        $plantWrapper->save();

        //话题热度计算
        if (module_exists('shusy_hot_topic')) {
            foreach ($topics as $topic) {
                $es = shusy_hot_topic_load_multiple(FALSE, ['topic_id' => $topic]);
                if (!empty($es)) {
                    $e = reset($es);
                } else {
                    $e = new ShusyHotTopic();
                    $e->topic_id = $topic;
                }
                if ($e instanceof ShusyHotTopic) {
                    $e->number++;
                    $e->save();
                }
            }
        }

        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param string $title
     * @return array
     * @OA\Post(
     *    path="/common/submit_new_topic",
     *    summary="创建新话题 common/submit_new_topic",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"title"},
     *        @OA\Property(
     *          property="title",
     *          type="string",
     *          description="话题标题",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="topic",
     *         type="object",
     *         ref="#/components/schemas/TopicItem"
     *       ),
     *     )
     *   )
     * )
     */
    function submit_new_topic(string $title)
    {
        $title = trim($title);
        $es = shusy_topic_load_multiple(FALSE, ['title' => $title]);
        if (empty($es)) {
            $e = new ShusyTopic();
            $e->title = $title;
            $e->status = 1;
            $e->save();
            return [
                'code' => 0,
                'msg' => 'ok',
                'topic' => TopicItem::get($e->id),
            ];
        }
        return [
            'code' => 1,
            'msg' => '话题已存在',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/switch_city",
     *    summary="切换城市 common/switch_city",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id",},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="CityItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function switch_city(int $id)
    {
        $uid = $this->getUid();
        $city = shusy_city_load($id);
        if ($city instanceof ShusyCity && $city->status == 1) {
            cache_set("in_city_{$uid}", $city->id, 'cache_shushengyuan', REQUEST_TIME + (24 * 60 * 60));
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '城市不存在或未开通服务',
        ];
    }

    /**
     * @param int $id
     * @param int $qty
     * @return array
     * @OA\Post(
     *    path="/common/submit_add_cart",
     *    summary="添加到购物车 common/submit_add_cart",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","qty"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="Standard.id",
     *        ),
     *        @OA\Property(
     *          property="qty",
     *          type="integer",
     *          description="购买数量",
     *          default="1"
     *        ),
     *        @OA\Property(
     *          property="type",
     *          type="integer",
     *          description="购买类型 0 正常 1 拼团 2 秒杀",
     *          default="0"
     *        ),
     *        @OA\Property(
     *          property="options",
     *          type="array",
     *          description="页面参数",
     *          @OA\Items(type="integer"),
     *          default="[]"
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     * 1 默认详情  2 秒杀详情 3 去拼团 4 拼团详情 5 平台供应
     */
    function submit_add_cart(int $id, int $qty = 1, int $type = 0, array $options = [])
    {
        $uid = $this->getUid();
        $standard = shusy_product_standard_load($id);
        if ($standard instanceof ShusyProductStandard && $standard->status == 1) {
            $productWrapper = $standard->wrapper();
            $store = $productWrapper->product->store->value();
            if ($store instanceof ShusyStore) {
                $cart = $this->getCart($uid, $store->id);
                //$amountType 类型 0 正常 1 VIP 2 店铺进货 3 拼团 4 秒杀
                $amountType = 0;
                switch ($type) {
                    case 1:
                        $amountType = 0;
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    case 5:
                        $amountType = 2;
                        break;
                }
                $amount = $standard->amount;
                [$spread_type, $spread_anchor_uid] = $this->getSpreadVars();
                $this->addCart($cart, $standard, $amount, $qty, 0, $amountType, $spread_type, $spread_anchor_uid);
            }
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '商品不存在或已下架',
        ];
    }

    /**
     * @param int $id
     * @param int $qty
     * @param int $type
     * @param int $pting
     * @return array
     * @OA\Post(
     *    path="/common/submit_buy_now",
     *    summary="立即购买 common/submit_buy_now",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","qty"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="Standard.id",
     *        ),
     *        @OA\Property(
     *          property="qty",
     *          type="integer",
     *          description="购买数量",
     *          default="1"
     *        ),
     *        @OA\Property(
     *          property="type",
     *          type="integer",
     *          description="1 默认详情  2 秒杀详情 3 去拼团 4 拼团详情 5 平台供应",
     *          default="0"
     *        ),
     *        @OA\Property(
     *          property="pting",
     *          type="integer",
     *          description="如果是参与其他人的拼团需要传 ProductPtingItem.id",
     *          default="0"
     *        ),
     *        @OA\Property(
     *          property="options",
     *          type="array",
     *          description="页面参数",
     *          @OA\Items(type="integer"),
     *          default="[]"
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_buy_now(int $id, int $qty = 1, int $type = 0, int $pting = 0, array $options = [])
    {
        $db_transaction = db_transaction();
        try {
            $uid = $this->getUid();
            $standard = shusy_product_standard_load($id);
            if ($standard instanceof ShusyProductStandard && $standard->status == 1) {
                $standardWrapper = $standard->wrapper();
                if ($standardWrapper->stock->value() >= $qty) {
                    $productWrapper = $standard->wrapper();
                    $store = $productWrapper->product->store->value();
                    if ($store instanceof ShusyStore) {
                        $order = $this->createOrder($uid, $store->id);

                        $amountType = $type;
                        $amount = $standard->amount;

                        //1 默认详情 2 秒杀详情 3 去拼团 4 拼团详情 5 平台供应 6 内部专享价
                        //目标价格类型 0 正常 1 VIP 2 店铺进货 3 拼团 4 秒杀
                        switch ($type) {
                            case 1:
                                $amountType = 0;
                                break;
                            case 2:
                                $order->type = 2;
                                $amountType = 4;
                                $amount = $productWrapper->msamount->value();
                                if (module_exists('shusy_maxms')) {
                                    $maxes = shusy_maxms_load_multiple(FALSE, [
                                        'uid' => $uid,
                                        'product_standard_id' => $id,
                                    ]);
                                    if (!empty($maxes)) {
                                        $maxe = reset($maxes);
                                    } else {
                                        $maxe = new ShusyMaxms();
                                        $maxe->uid = $uid;
                                        $maxe->product_standard_id = $id;
                                    }
                                    if ($maxe instanceof ShusyMaxms) {
                                        $number = $productWrapper->miaosha->number->value();
                                        if ($number > 0 && $maxe->number >= $number) {
                                            throw new Exception('超过最大秒杀次数');
                                        }
                                        $maxe->number++;
                                        $maxe->save();
                                    }
                                }
                                break;
                            case 3:
                            case 4:
                                $order->type = 1;
                                $amountType = 3;
                                $amount = $productWrapper->ptamount->value();
                                //如果是参与
                                if ($pting > 0) {
                                    $player = new ShusyPintuanPlayer();
                                    $player->pintuan_id = $pting;
                                    $player->uid = $uid;
                                    $player->status = 0;
                                    $player->save();
                                } else {
                                    //自己拼
                                    $pt = new ShusyPintuan();
                                    $pt->product_id = $standard->product_id;
                                    $pt->validity = REQUEST_TIME + (24 * 60 * 60);
                                    $pt->number = $standardWrapper->product->pintuan->number->value();
                                    $pt->status = 0;
                                    $pt->uid = $uid;
                                    $pt->save();

                                    $player = new ShusyPintuanPlayer();
                                    $player->pintuan_id = $pt->id;
                                    $player->uid = $uid;
                                    $player->status = 0;
                                    $player->save();
                                }
                                $opt = new ShusyStoreOrderPintuan();
                                $opt->pintuan_player_id = $player->id;
                                $opt->store_order_id = $order->id;
                                $opt->save();
                                break;
                            case 5:
                                //计算采购价 如果非采购商品要修改成普通购买
                                //$amountType 类型 0 正常 1 VIP 2 店铺进货 3 拼团 4 秒杀
                                $amountType = 2;
                                break;
                        }
                        [$spread_type, $spread_anchor_uid] = $this->getSpreadVars();
                        $this->addCart($order, $standard, $amount, $qty, 0, $amountType, $spread_type, $spread_anchor_uid);
                        //立即购买的算待支付
                        $order->status = 2;
                        $order->save();
                        //扣库存 在订单创建完成之后
                        $standard->stockChange(-$qty);

                        $cid = "payment_{$uid}";
                        $this->cacheSet($cid, [$order->id]);

                        return [
                            'code' => 0,
                            'msg' => 'ok',
                        ];
                    }
                    throw new Exception('商品未归属店铺');
                }
                throw new Exception('库存不足');
            }
            throw new Exception('商品不存在或已下架');
        } catch (Exception $exception) {
            $db_transaction->rollback();
            return [
                'code' => 2,
                'msg' => $exception->getMessage(),
            ];
        }
    }

    /**
     * @param int $uid
     * @param int $store_id
     * @return \Drupal\shusy_store_order\Entity\ShusyStoreOrder
     */
    protected function getCart(int $uid, int $store_id)
    {
        $es = shusy_store_order_load_multiple(FALSE, [
            'uid' => $uid,
            'store_id' => $store_id,
            'status' => 1,
        ]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyStoreOrder;
            $e->uid = $uid;
            $e->store_id = $store_id;
            $e->status = 1;
            $e->save();
        }
        return $e;
    }

    /**
     * @param \Drupal\shusy_store_order\Entity\ShusyStoreOrder $storeOrder
     * @param \Drupal\shusy_product\Entity\ShusyProductStandard $standard
     * @param int $amount 价格
     * @param int $qty 数量
     * @param int $source ShusyStoreOrderLine.id
     * @param int $type 目标价格类型 0 正常 1 VIP 2 店铺进货 3 拼团 4 秒杀 6 内部专享价
     * @throws \EntityMetadataWrapperException
     * 加入购物车 合并相同价格的产品
     */
    protected function addCart(ShusyStoreOrder $storeOrder, ShusyProductStandard $standard, int $amount, int $qty, int $source, int $type, int $spread_type, int $spread_anchor_uid)
    {
        $standardWrapper = $standard->wrapper();
        $product = $standardWrapper->product->value();
        $context = [$storeOrder, $product, $standard, $amount, $type];

        $amounts = [];
        $amounts[] = [
            'type' => $type,
            'amount' => $amount,
        ];
        if ($source == 0) {
            drupal_alter('shushengyuan_order_amount_preprocess', $amounts, $context);
        }
        //获取所有价格信息 取一个最小的
        usort($amounts, function ($a, $b) {
            $a_weight = (is_array($a) && isset($a['amount'])) ? $a['amount'] : 0;
            $b_weight = (is_array($b) && isset($b['amount'])) ? $b['amount'] : 0;
            if ($a_weight == $b_weight) {
                return 0;
            }
            return ($a_weight < $b_weight) ? -1 : 1;
        });
        //获取价格最低价格
        $item = array_shift($amounts);
        $type = $item['type'];
        $amount = $item['amount'];

        $storeOrderWrapper = $storeOrder->wrapper();
        $lines = $storeOrderWrapper->lines;
        if ($lines instanceof EntityListWrapper) {
            foreach ($lines as $line) {
                //产品类型 单价相同 同一个规格
                if ($line->type->value() == 'product' && $line->amount->value() == $amount && $line->standard->id->value() == $standard->id) {
                    $line = $line->value();
                    $line->qty += $qty;
                    $line->lid = $source;
                    $line->save();
                    return;
                }
            }
        }
        $line = new ShusyStoreOrderLine();
        $line->type = 'product';
        $line->store_order_id = $storeOrder->id;
        $line->name = $standard->getProductName();
        $line->amount = $amount;
        $line->amount_type = $type;

        $line->spread_type = $spread_type;
        $line->spread_anchor_uid = $spread_anchor_uid;

        $line->qty = $qty;
        $line->status = 1;
        $line->lid = $source;
        $line->save();
        $lineProduct = new ShusyStoreOrderLineProduct();
        $lineProduct->is_service = $standardWrapper->product->is_service->value();
        $lineProduct->type = $type;
        $lineProduct->store_order_line_id = $line->id;
        $lineProduct->product_standard_id = $standard->id;
        $lineProduct->save();
        //加入购物车总是计算总价
        $storeOrder->upTotal = TRUE;
        //计算总价
        $storeOrder->save();

        if (module_exists('shusy_order_product_first_coupon')) {
            $t = shusy_order_product_first_coupon_new_single(FALSE, [
                'product_standard_id' => $standard->id,
                'uid' => $this->getUid(),
            ]);
            $t->product_standard_id = $standard->id;
            $t->uid = $this->getUid();
            $t->store_order_line_id = $line->id;
            $t->save();
        }

    }

    /**
     * @param int $uid
     * @param int $store_id
     * @return \Drupal\shusy_store_order\Entity\ShusyStoreOrder
     * 创建订单 待支付状态
     */
    protected function createOrder(int $uid, int $store_id)
    {
        $order = new ShusyStoreOrder;
        $order->uid = $uid;
        $order->store_id = $store_id;
        //状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
        $order->status = 2;
        $order->save();
        return $order;
    }

    /**
     * @param array $lids
     * @return array
     * @OA\Post(
     *    path="/common/select_line_item_payment",
     *    summary="选择购物车中的部分产品进行支付 common/select_line_item_payment",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"lids",},
     *        @OA\Property(
     *          property="lids",
     *          type="array",
     *          description="购物车行项line_item_ids",
     *          @OA\Items(type="integer"),
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function select_line_item_payment(array $lids)
    {
        $db_transaction = db_transaction();
        try {
            $uid = $this->getUid();
            $list = [];
            $shippings = $all = shusy_store_order_shipping_type_options();
            foreach ($lids as $lid) {
                $line = shusy_store_order_line_load($lid);
                if ($line instanceof ShusyStoreOrderLine && $line->status == 1 && $line->type == 'product') {
                    $qty = $line->qty;
                    $lineWrapper = $line->wrapper();
                    $standardWrapper = $lineWrapper->standard;
                    $standard = $standardWrapper->value();
                    if ($standardWrapper->stock->value() >= $qty) {
                        $standard->stockChange(-$qty);
                        $store = $lineWrapper->order->store->value();
                        //验证库存并扣减对应库存量
                        if ($store instanceof ShusyStore) {
                            if (!isset($list[$store->id])) {
                                $order = $this->createOrder($uid, $store->id);
                                $list[$store->id] = $order;
                            }
                            if (isset($list[$store->id])) {
                                $type = $lineWrapper->amount_type->value();
                                //此处已经是折后价格
                                $this->addCart($list[$store->id], $lineWrapper->standard->value(), $line->amount, $line->qty, $line->id, $type, $line->spread_type, $line->spread_anchor_uid);
                            }
                        }
                    } else {
                        throw new Exception(t('@name @standard 库存不足', [
                            '@name' => $standardWrapper->product->name->value(),
                            '@standard' => $standard->standard,
                        ]));
                    }
                    //验证是否具有相同的配送方式
                    $productId = $lineWrapper->standard->product_id->value();
                    $tmps = shusy_product_shipping_product_shippings($productId);
                    if (empty($tmps)) {
                        $tmps = $all;
                    }
                    $shippings = array_intersect_key($shippings, $tmps);
                    if (empty($shippings)) {
                        throw new Exception("当前结算组合没有可用的配送方式.");
                    }
                }
            }
            $cache = [];
            foreach ($list as $item) {
                $cache[] = $item->id;
            }
            $cid = "payment_{$uid}";
            $this->cacheSet($cid, $cache);
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        } catch (Exception $exception) {
            $db_transaction->rollback();
            return [
                'code' => 2,
                'msg' => $exception->getMessage(),
            ];
        }
    }

    /**
     * @param int $lid
     * @param int $qty
     * @return array
     * @OA\Post(
     *    path="/common/submit_modify_qty",
     *    summary="修改购物车商品数量 common/submit_modify_qty",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"lid","qty"},
     *        @OA\Property(
     *          property="lid",
     *          type="integer",
     *          description="line_item_id",
     *        ),
     *        @OA\Property(
     *          property="qty",
     *          type="integer",
     *          description="修改后的数量",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_modify_qty(int $lid, int $qty)
    {
        $line = shusy_store_order_line_load($lid);
        if ($line instanceof ShusyStoreOrderLine && $line->type == 'product' && $line->uid == $this->getUid()) {
            $line->qty = $qty;
            $line->save();
            $order = shusy_store_order_load($line->store_order_id);
            if ($order instanceof ShusyStoreOrder) {
                //重新计算订单总价
                $order->save();
            }
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '项不正确',
        ];
    }

    /**
     * @param array $lids
     * @return array
     * @OA\Post(
     *    path="/common/submit_delete_lines",
     *    summary="从购物车删除产品 common/submit_delete_lines",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"lids",},
     *        @OA\Property(
     *          property="lids",
     *          type="array",
     *          description="购物车行项line_item_ids",
     *          @OA\Items(type="integer"),
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_delete_lines(array $lids)
    {
        foreach ($lids as $lid) {
            $line = shusy_store_order_line_load($lid);
            if ($line instanceof ShusyStoreOrderLine && $line->type == 'product' && $line->uid == $this->getUid()) {
                $line->status = 0;
                $line->save();
                $order = shusy_store_order_load($line->store_order_id);
                if ($order instanceof ShusyStoreOrder) {
                    //重新计算订单总价
                    $order->save();
                }
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param array $address
     * @return array
     * @OA\Post(
     *    path="/common/submit_switch_address",
     *    summary="切换所有结算订单的收货地址 并计算运费 common/submit_switch_address",
     *    tags={"v1.0","v2.1"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"address"},
     *        @OA\Property(
     *          property="address",
     *          type="object",
     *          description="微信小程序返回的地址信息",
     *          ref="#/components/schemas/WxAddress"
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="list",
     *         type="array",
     *         description="结算订单列表",
     *         @OA\Items(ref="#/components/schemas/OrderPayment")
     *       ),
     *     )
     *   )
     * )
     */
    function submit_switch_address(array $address)
    {
        $list = [];
        $uid = $this->getUid();
        $cid = "inPayment_{$uid}";
        $cache = $this->cacheGet($cid);
        if (!empty($cache)) {
            foreach ($cache->data as $datum) {
                $list[] = $this->switchAddress($datum, $address);
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
            'list' => $list,
        ];
    }

    protected function switchAddress(int $id, array $address)
    {
        $uid = $this->getUid();
        $order = shusy_store_order_load($id);
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            //切换收货地址
            $es = shusy_store_order_address_load_multiple(FALSE, ['store_order_id' => $id]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new ShusyStoreOrderAddress();
                $e->store_order_id = $id;
            }
            $e->username = $address['userName'];
            $e->nationalcode = $address['nationalCode'];
            $e->telnumber = $address['telNumber'];
            $e->provincename = $address['provinceName'];
            $e->cityname = $address['cityName'];
            $e->countyname = $address['countyName'];
            $e->detailinfo = $address['detailInfo'];
            $e->postalcode = $address['postalCode'];
            $e->save();

            //检查订单是否是快递配送方式
            $weightShipping = FALSE;
            $orderWrapper = $order->wrapper();
            $commerce_line_items = $orderWrapper->lines;
            if ($commerce_line_items instanceof EntityListWrapper) {
                foreach ($commerce_line_items->getIterator() as $item) {
                    if ($item->type->value() == 'shipping' && $item->shipping->shipping_type->value() == 'commerce_weight_shipping') {
                        $weightShipping = TRUE;
                    }
                }
            }
            if ($weightShipping) {
                //重新计算运费
                $this->clearShippingLine($order);
                $this->addressComputeShipping($e, $order);
            }

            $order->save();
        }
        return OrderPayment::get($id);
    }


    protected function clearShippingLine(ShusyStoreOrder $shusyStoreOrder)
    {
        $lines = $shusyStoreOrder->lines();
        foreach ($lines as $line) {
            if ($line instanceof ShusyStoreOrderLine && $line->type == 'shipping') {
                $line->status = 0;
                $line->save();
            }
        }
    }


    /**
     * @param int $id
     * @param int $shipping
     * @return array
     * @OA\Post(
     *    path="/common/submit_switch_shipping",
     *    summary="切换配送方式 common/submit_switch_shipping",
     *    tags={"v1.0","v2.1"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","shipping"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="Order.id",
     *        ),
     *        @OA\Property(
     *          property="shipping",
     *          type="integer",
     *          description="配送方式 0 到店自提 1 快达 2 快递",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="list",
     *         type="array",
     *         description="结算订单列表",
     *         @OA\Items(ref="#/components/schemas/OrderPayment")
     *       ),
     *     )
     *   )
     * )
     */
    function submit_switch_shipping(int $id, int $shipping)
    {
        try {
            $this->switchShipping($id, $shipping);
            $list = [];
            $uid = $this->getUid();
            $cid = "inPayment_{$uid}";
            $cache = $this->cacheGet($cid);
            if (!empty($cache)) {
                foreach ($cache->data as $datum) {
                    $list[] = OrderPayment::get($datum);
                }
            }
            return [
                'code' => 0,
                'msg' => 'ok',
                'list' => $list,
            ];
        } catch (ApiException $exception) {
            return [
                'code' => 1,
                'msg' => $exception->getMessage(),
            ];
        }
    }

    /**
     * @param int $id
     * @param int $cid
     * @return array
     * @OA\Post(
     *   path="/common/submitUseCoupon",
     *   summary="使用优惠券 common/submitUseCoupon",
     *   tags={"v3.1",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"id","cid"},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="Order.id",
     *       ),
     *       @OA\Property(
     *         property="cid",
     *         type="integer",
     *         description="优惠券持有ID",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitUseCoupon(int $id, int $cid)
    {
        $uid = $this->getUid();
        $coupon = shusy_store_coupon_hold_load($cid);
        if ($coupon instanceof ShusyStoreCouponHold && $uid == $coupon->uid && $coupon->status == 0) {
            $order = shusy_store_order_load($id);
            if ($order instanceof ShusyStoreOrder && $uid == $order->uid) {
                if ($order->amount < $coupon->condition_min) {
                    return [
                        'code' => 1,
                        'msg' => t("运费未满 ¥@min，无法使用优惠券", ['@min' => $this->convertYuan($coupon->condition_min)]),
                    ];
                }
                //检查优惠券有效期
                if ($coupon->validity_start <= REQUEST_TIME && REQUEST_TIME <= $coupon->validity_end) {

                    $lines = shusy_store_order_line_load_multiple(FALSE, [
                        'store_order_id' => $order->id,
                        'type' => 'coupon',
                    ]);
                    if (!empty($lines)) {
                        $line = reset($lines);
                    } else {
                        $line = new ShusyStoreOrderLine();
                        $line->store_order_id = $order->id;
                        $line->type = 'coupon';
                    }
                    $line->status = 1;
                    $line->name = '优惠券';
                    $line->qty = 1;
                    $line->amount = -$coupon->amount;
                    $line->total = $line->qty * $line->amount;
                    $line->payment = 1;
                    $line->save();

                    $order->save();

                    //记录优惠券与line item 关联用于优惠券核销
                    $cl = shusy_store_coupon_line_new_single(FALSE, ['order_line_item_id' => $line->id]);
                    $cl->order_line_item_id = $line->id;
                    $cl->coupon_hold_id = $coupon->id;
                    $cl->save();

                    return [
                        'code' => 0,
                        'msg' => 'ok',
                    ];
                }
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
            return [
                'code' => 1,
                'msg' => '订单不正确',
            ];
        }
        return [
            'code' => 1,
            'msg' => '优惠券无效',
        ];
    }

    /**
     * @param string $name
     * @param string $address
     * @param float $latitude
     * @param float $longitude
     * @return array
     * @OA\Post(
     *   path="/common/submitChooseLocation",
     *   summary="结算提交选择经纬度 common/submitChooseLocation",
     *   tags={"v2.3",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"name","address","latitude","longitude"},
     *       @OA\Property(
     *         property="name",
     *         type="string",
     *         description="位置名称",
     *       ),
     *       @OA\Property(
     *         property="address",
     *         type="string",
     *         description="详细地址",
     *       ),
     *       @OA\Property(
     *         property="latitude",
     *         type="string",
     *         description="纬度",
     *       ),
     *       @OA\Property(
     *         property="longitude",
     *         type="string",
     *         description="经度",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitChooseLocation(string $name, string $address, float $latitude, float $longitude)
    {
        $uid = $this->getUid();
        $cid = "inPayment_{$uid}";
        $cache = $this->cacheGet($cid);
        if (!empty($cache)) {
            foreach ($cache->data as $datum) {
                $this->switchLocation($datum, $name, $address, $latitude, $longitude);
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    protected function switchLocation(int $id, string $name, string $address, float $latitude, float $longitude)
    {
        $order = shusy_store_order_load($id);
        if ($order instanceof ShusyStoreOrder) {
            //切换收货地址
            $es = shusy_store_order_location_load_multiple(FALSE, ['store_order_id' => $id]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new ShusyStoreOrderLocation();
                $e->store_order_id = $id;
            }
            $e->name = $name;
            $e->address = $address;
            $e->latitude = $latitude;
            $e->longitude = $longitude;
            $e->save();
        }
    }

    /**
     * @param int $id
     * @param string $note
     * @return array
     * @OA\Post(
     *    path="/common/submit_order_note",
     *    summary="提交订单备注 common/submit_order_note",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id",},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="Order.id",
     *        ),
     *        @OA\Property(
     *          property="note",
     *          type="string",
     *          description="订单备注",
     *          default=""
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_order_note(int $id, string $note = "")
    {
        $uid = $this->getUid();
        $order = shusy_store_order_load($id);
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            $es = shusy_store_order_note_load_multiple(FALSE, ['store_order_id' => $order->id]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new ShusyStoreOrderNote();
                $e->store_order_id = $order->id;
            }
            if ($e instanceof ShusyStoreOrderNote) {
                $e->note = $note;
                $e->save();
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @param int $deduct
     * @return array
     * @OA\Post(
     *    path="/common/submit_switch_gold_deduct",
     *    summary="切换金币抵扣 common/submit_switch_gold_deduct",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","deduct",},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="Order.id",
     *        ),
     *        @OA\Property(
     *          property="deduct",
     *          type="integer",
     *          description="是否抵扣 0 不抵扣 1 抵扣",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="order",
     *         type="object",
     *         ref="#/components/schemas/OrderPayment"
     *       ),
     *     )
     *   )
     * )
     */
    function submit_switch_gold_deduct(int $id, int $deduct)
    {
        //@todo 成本由平台承担 还是 商家承担??? 金币来源??? 暂时不做
        $uid = $this->getUid();
        $order = shusy_store_order_load($id);
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            $lines = $order->lines();
            foreach ($lines as $line) {
                if ($line instanceof ShusyStoreOrderLine && $line->type == 'gold') {
                    $line->status = 0;
                    $line->save();
                }
            }
            //是否抵扣 0 不抵扣 1 抵扣
            switch ($deduct) {
                case 0:

                    break;
                case 1:

                    break;
                default:
                    return [
                        'code' => 1,
                        'msg' => '选择不正确',
                    ];
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
            'order' => OrderPayment::get($id),
        ];
    }

    /**
     * @param array $ids
     * @return array
     * @OA\Post(
     *    path="/common/submit_payment_order",
     *    summary="结算订单 common/submit_payment_order",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"ids"},
     *        @OA\Property(
     *          property="ids",
     *          type="array",
     *          description="Order.id 需要结算的订单ID",
     *          @OA\Items(type="integer"),
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_payment_order(array $ids)
    {
        $uid = $this->getUid();
        $cache = [];
        foreach ($ids as $id) {
            $cache[] = $id;
            $this->refreshOrderValidity($id);
        }
        //刷新订单支付有效期
        $cid = "inPayment_{$uid}";
        $this->cacheSet($cid, $cache);
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @return array
     * @throws \Exception
     * @OA\Post(
     *    path="/common/submit_order_wxpay",
     *    summary="微信支付订单 common/submit_order_wxpay",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="unify",
     *         description="无需支付时返回 false 快达被拒绝后,选择其它配送方式重走支付流程的情况",
     *         type="object",
     *         ref="#/components/schemas/WxPayUnify"
     *       ),
     *     )
     *   )
     * )
     */
    function submit_order_wxpay()
    {
        //检查订单数据
        $uid = $this->getUid();
        $cid = "inPayment_{$uid}";
        $cache = $this->cacheGet($cid);
        $total_fee = 0;
        $ids = [];
        if (!empty($cache)) {
            foreach ($cache->data as $datum) {
                $order = shusy_store_order_load($datum);
                if ($order instanceof ShusyStoreOrder) {
                    //服务订单不验证收货地址与配送方式
                    $orderWrapper = $order->wrapper();
                    $is_service = TRUE;
                    $lines = $orderWrapper->lines;
                    try {
                        foreach ($lines as $line) {
                            if ($line->type->value() == 'product') {
                                $tmp = (bool)$line->standard->product->is_service->value();
                                if (!$tmp) {
                                    $is_service = FALSE;
                                }
                            }
                        }
                    } catch (Exception $exception) {

                    }

                    $address = $orderWrapper->address->value();
                    //是否 设置了收货地址
                    if (!$is_service && !($address instanceof ShusyStoreOrderAddress)) {
                        return [
                            'code' => 1,
                            'msg' => '请选择收货地址',
                        ];
                    }
                    //是否选择了配送方式
                    $checkShipping = FALSE;
                    //配送方式 -1 未选择 0 到店自提 1 快达 2 快递
                    $lines = $orderWrapper->lines;
                    try {
                        foreach ($lines as $line) {
                            if ($line->type->value() == 'shipping') {
                                $shipping_type = $line->shipping->shipping_type->value();

                                //0 到店自提 1 快达 2 快递
                                switch ($shipping_type) {
                                    case 'shusy_service':
                                    case 'commerce_weight_shipping':
                                        $checkShipping = TRUE;
                                        break;
                                    case 'shusy_errand':
                                        //如果有快达服务 需要检查是否设置了经纬度地址
                                        $location = $orderWrapper->location->value();
                                        if ($location instanceof ShusyStoreOrderLocation) {
                                            $checkShipping = TRUE;
                                        } else {
                                            return [
                                                'code' => 1,
                                                'msg' => '请选择精准定位',
                                            ];
                                        }
                                        break;
                                    default:
                                        return [
                                            'code' => 1,
                                            'msg' => '请选择配送方式',
                                        ];
                                        break;
                                }
                            }
                        }
                    } catch (Exception $exception) {

                    }
                    if (!$is_service && !$checkShipping) {
                        return [
                            'code' => 1,
                            'msg' => '请选择配送方式',
                        ];
                    }


                    $lines = $order->lines();
                    foreach ($lines as $line) {
                        if ($line instanceof ShusyStoreOrderLine) {
                            if ($line->lid > 0) {
                                $cartLine = shusy_store_order_line_load($line->lid);
                                if ($cartLine instanceof ShusyStoreOrderLine) {
                                    $cartLine->status = 0;
                                    $cartLine->save();
                                }
                            }
                        }
                    }
                    //切换支付状态 状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
                    $order->status = 2;
                    $order->save();
                    //获取支付记录对象
                    $pay = shusy_store_order_pay_create($order, 'wx');
                    $wxPay = shusy_pay_wx_create($pay);
                    $ids[] = $wxPay->id;
                    $total_fee += $pay->amount;
                }
            }
        }
        $this->cacheClear($cid);
        $ids = serialize($ids);
        if ($total_fee > 0) {
            // var_dump($total_fee);exit;
            $wxController = new WxPayMiniPayController();
            $unify = $wxController->orderUnifyAndBridgeConfig('shushengyuan', '舒生元订单', $this->getOpenId(), $total_fee, ip_address(), "order|{$uid}|{$ids}", WX_PAY_MINIPAY);
            return [
                'code' => 0,
                'msg' => 'ok',
                'unify' => $unify,
            ];
        }
        return [
            'code' => 0,
            'msg' => 'ok',
            'unify' => FALSE,
        ];
    }

    protected function checkShipping($lines)
    {
        //配送方式 -1 未选择 0 到店自提 1 快达 2 快递
        try {
            foreach ($lines as $line) {
                if ($line->type->value() == 'shipping') {
                    $shipping_type = $line->shipping->shipping_type->value();
                    switch ($shipping_type) {
                        case 'shusy_service':
                            return 0;
                        case 'shusy_errand':
                            return 1;
                        case 'commerce_weight_shipping':
                            return 2;
                    }
                }
            }
        } catch (Exception $exception) {
            watchdog_exception(__FUNCTION__, $exception);
        }
        return -1;
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submit_close_order",
     *    summary="取消订单 common/submit_close_order",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="MyOrderItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_close_order(int $id)
    {
        $order = shusy_store_order_load($id);
        $uid = $this->getUid();
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            if (in_array($order->status, [2])) {
                //状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
                $order->status = 0;
                $order->save();
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
            return [
                'code' => 1,
                'msg' => '订单状态不正确',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submitDelOrder",
     *    summary="删除订单 common/submitDelOrder",
     *    tags={"v1.0","v2.0"},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="MyOrderItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitDelOrder(int $id)
    {
        $order = shusy_store_order_load($id);
        $uid = $this->getUid();
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            if (!in_array($order->status, [1, 2, 3, 4])) {
                //状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交 8 删除
                $order->status = 8;
                $order->save();
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
            return [
                'code' => 1,
                'msg' => '订单状态不正确',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param int $id
     * @OA\Post(
     *    path="/common/submit_confirm_receipt",
     *    summary="确认收货 common/submit_confirm_receipt",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="MyOrderItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     * @return array
     */
    function submit_confirm_receipt(int $id)
    {
        $order = shusy_store_order_load($id);
        $uid = $this->getUid();
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            if ($order->status == 4) {
                //状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
                $order->status = 5;
                $order->save();
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
            return [
                'code' => 1,
                'msg' => '订单状态不正确',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param int $id
     * @param array $comments
     * @return array
     * @throws \EntityMetadataWrapperException
     * @OA\Post(
     *    path="/common/submit_order_comment",
     *    summary="提交评论 common/submit_order_comment",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","comments"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="MyOrderItem.id",
     *        ),
     *        @OA\Property(
     *          property="comments",
     *          type="array",
     *          description="评论数组",
     *          @OA\Items(ref="#/components/schemas/PostCommentItem")
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_order_comment(int $id, array $comments)
    {
        $order = shusy_store_order_load($id);
        $uid = $this->getUid();
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            if ($order->status == 5) {
                //状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
                $order->status = 6;
                $order->save();
                foreach ($comments as $comment) {
                    $lid = $comment['lid'];
                    $score = $comment['score'];
                    $content = $comment['content'];
                    $fids = $comment['fids'];
                    $line = shusy_store_order_line_load($lid);
                    if ($line instanceof ShusyStoreOrderLine) {
                        $lineWrapper = $line->wrapper();

                        $shusyComment = new ShusyProductComment();
                        $shusyComment->uid = $uid;
                        $shusyComment->product_id = $lineWrapper->standard->product_id->value();
                        $shusyComment->score = $score;
                        $shusyComment->has_img = empty($fids) ? 0 : 1;
                        $shusyComment->content = $content;
                        $shusyComment->status = 0;
                        $shusyComment->save();

                        $imgs = [];
                        $field_name = 'field_images';
                        $dir = $this->filePrepareDirectory('shusy_product_comment', $field_name, 'shusy_product_comment');
                        foreach ($fids as $fid) {
                            $file = file_load($fid);
                            $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
                            $file = file_move($file, "{$dir}/{$this->getUid()}_comment_{$fid}.{$ext}");
                            file_usage_add($file, 'shusy_product_comment', 'shusy_product_comment', $file->fid);
                            $imgs[] = ['fid' => $file->fid];
                        }
                        $shusyCommentWrapper = $shusyComment->wrapper();
                        $shusyCommentWrapper->field_images->set($imgs);
                        $shusyCommentWrapper->save();
                    }
                }
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
            return [
                'code' => 1,
                'msg' => '订单状态不正确',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param string $name
     * @param string $birthday
     * @param string $profession
     * @param string $phone
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submit_vip",
     *    summary="平台会员申请 common/submit_vip",
     *    tags={"v1.0","v2.0"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"name","birthday","profession","phone","id"},
     *        @OA\Property(
     *          property="name",
     *          type="string",
     *          description="姓名",
     *        ),
     *        @OA\Property(
     *          property="birthday",
     *          type="string",
     *          description="生日 YYYY-MM-DD 格式",
     *        ),
     *        @OA\Property(
     *          property="profession",
     *          type="string",
     *          description="职业",
     *        ),
     *        @OA\Property(
     *          property="phone",
     *          type="string",
     *          description="电话",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_vip(string $name, string $birthday, string $profession, string $phone)
    {
        try {
            $uid = $this->getUid();
            $vip = $this->getDefaultVip();
            if ($vip instanceof ShusyVip) {
                $es = shusy_vip_bind_load_multiple(FALSE, ['uid' => $uid]);
                if (!empty($es)) {
                    $e = reset($es);
                } else {
                    $e = new ShusyVipBind();
                    $e->uid = $uid;
                }
                $e->name = $name;
                $e->birthday = strtotime($birthday);
                $e->profession = $profession;
                $e->phone = $phone;
                $e->status = 1;
                $e->vip_id = $vip->id;
                $e->save();
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
            return [
                'code' => 1,
                'msg' => '没有设置VIP',
            ];
        } catch (Exception $exception) {
            return [
                'code' => 1,
                'msg' => '系统错误',
            ];
        }
    }

    /**
     * @return \Drupal\shusy_vip\Entity\ShusyVip|false
     * 计算需要绑定哪个VIP 如果没有默认 则自动绑定 累计金额最低的
     */
    protected function getDefaultVip()
    {
        $vip = FALSE;
        $vips = shusy_vip_load_multiple(FALSE, [
            'status' => 1,
        ]);
        if (!empty($vips)) {
            foreach ($vips as $item) {
                if ($item instanceof ShusyVip) {
                    if ($item->is_default == 1) {
                        return $item;
                    }
                    if ($vip === FALSE) {
                        $vip = $item;
                    } else {
                        if ($item->amount <= $vip->amount) {
                            $vip = $item;
                        }
                    }
                }
            }
        }
        return $vip;
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submit_close_errand_order",
     *    summary="关闭快达订单 common/submit_close_errand_order",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="ErrandOrder.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_close_errand_order(int $id)
    {
        $errand = $this->getErrand();
        if ($errand instanceof ShusyErrand) {
            $errandOrder = shusy_errand_order_load($id);
            if ($errandOrder instanceof ShusyErrandOrder && $errandOrder->city_id == $errand->city_id) {
                $errandOrder->status = 3;
                //关闭快达订单 后续处理逻辑 重走支付流程 根据 配送类型 支付对应差距
                $errandOrder->save();
                $order = shusy_store_order_load($errandOrder->store_order_id);
                if ($order instanceof ShusyStoreOrder) {
                    //清理配送方式选择
                    $this->clearShippingLine($order);
                    //切换支付状态 状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
                    $order->status = 2;
                    //重新计算费用
                    $order->save();
                }
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
        }
        return [
            'code' => 1,
            'msg' => '非快达人员',
        ];
    }

    /**
     * @param int $id
     * @param int $eid
     * @return array
     * @OA\Post(
     *    path="/common/submit_assign_errand_order",
     *    summary="快达订单分配 common/submit_assign_errand_order",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","eid"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="ErrandOrder.id",
     *        ),
     *        @OA\Property(
     *          property="eid",
     *          type="integer",
     *          description="ErrandItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_assign_errand_order(int $id, int $eid)
    {
        $uid = $this->getUid();
        $errand = shusy_errand_load($eid);
        $inErrand = $this->getErrand();
        if ($errand instanceof ShusyErrand && $inErrand instanceof ShusyErrand && $errand->errand_id == $inErrand->id) {
            $order = shusy_errand_order_load($id);
            if ($order instanceof ShusyErrandOrder && $order->city_id == $errand->city_id) {
                $order->errand_id = $errand->id;
                $order->status = 1;
                $order->save();
                //订单状态修改为待收货
                $userOrder = shusy_store_order_load($order->store_order_id);
                if ($userOrder instanceof ShusyStoreOrder) {
                    //状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交
                    if ($userOrder->status == 3) {
                        $userOrder->status = 4;
                        $userOrder->save();
                    }
                }
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
        }
        return [
            'code' => 1,
            'msg' => '非快达人员',
        ];
    }

    /**
     * @return array
     * @OA\Post(
     *    path="/common/submit_sign",
     *    summary="今日签到 common/submit_sign",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_sign()
    {
        $uid = $this->getUid();
        $in_day = $this->formatDate(REQUEST_TIME, 'Ymd');
        $es = shusy_sign_load_multiple(FALSE, ['uid' => $uid, 'in_day' => $in_day]);
        if (empty($es)) {

            $base = variable_get_value('shushengyuan:sign:base');
            $rule = variable_get_value('shushengyuan:sign:rule');
            $days = 0;

            //查找昨天是否签到 判断是否连续
            $query = new EntityFieldQuery();
            $query->entityCondition('entity_type', 'shusy_sign');
            $query->propertyCondition('uid', $uid);
            $prevDay = $this->formatDate(REQUEST_TIME - (24 * 60 * 60), 'Ymd');
            $query->propertyCondition('in_day', $prevDay);
            $query->propertyOrderBy('created', 'DESC');
            $query->range(0, 1);
            $result = $query->execute();
            $ids = [];
            if (!empty($result)) {
                foreach ($result['shusy_sign'] as $item) {
                    $ids[] = $item->id;
                }
            }
            if (!empty($ids)) {
                $id = reset($ids);
                $jSignBefore = entity_load_single('shusy_sign', $id);
                if ($jSignBefore instanceof ShusySign) {
                    $days = $jSignBefore->days;
                }
            }

            //解析签到规则
            $reward = 0;
            $list = $this->toRuleList($rule);
            if (isset($list[$days])) {
                $reward = $list[$days];
            }

            //如果连续大于规则天 不重置连续
            if ($days >= count($list)) {
                //$days = 0;
            } else {
                $days = $days + 1;
            }

            $gold = $base + $reward;
            points_to_uid($uid, t('签到获取'), 'point', $gold);

            $e = new ShusySign();
            $e->uid = $uid;
            $e->in_day = $in_day;
            $e->days = $days;
            $e->point = $gold;
            $e->save();

            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '今日已签到',
        ];
    }

    protected function toRuleList($string)
    {
        $values = [];
        $list = explode("\n", $string);
        $list = array_map('trim', $list);
        $list = array_filter($list, 'strlen');
        foreach ($list as $position => $text) {
            $values[] = $text;
        }
        return $values;
    }

    /**
     * @param float $amount
     * @param int $type
     * @return array
     * @OA\Post(
     *    path="/common/submit_cash",
     *    summary="提交提现申请 common/submit_cash",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"amount","type"},
     *        @OA\Property(
     *          property="amount",
     *          type="string",
     *          description="提现金额",
     *        ),
     *        @OA\Property(
     *          property="type",
     *          type="integer",
     *          description="提现方式 0 微信",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_cash(float $amount, int $type)
    {
        $uid = $this->getUid();
        $amount = floor($amount * 100);
        $income = points_get_total($uid, 'income');
        if ($income >= $amount && $amount > 0) {
            $t = variable_get_value('shushengyuan:income:service:charge');
            $sa = floor($t * $amount);
            $e = new ShusyCash();
            $e->type = 'income';
            $e->uid = $uid;
            $e->apply_amount = $amount;
            $e->amount = $amount - $sa;
            $e->service_amount = $sa;
            $e->status = 0;
            $e->info = '佣金提现';
            $e->save();

            points_to_uid($uid, '提现', 'income', -$amount);

            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '金额不足',
        ];
    }

    /**
     * @param float $amount
     * @param int $type
     * @return array
     * @OA\Post(
     *    path="/common/submitCash2",
     *    summary="提交提现申请 common/submitCash2",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"amount","type"},
     *        @OA\Property(
     *          property="amount",
     *          type="string",
     *          description="提现金额",
     *        ),
     *        @OA\Property(
     *          property="type",
     *          type="string",
     *          description="提现类型",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitCash2(float $amount, string $type)
    {
        $uid = $this->getUid();
        if ($amount < 10) {
            return [
                'code' => 2,
                'msg' => '最低单次提现10元',
            ];
        }
        switch ($type) {
            //佣金提现
            case 'income':
                return $this->submit_cash($amount, 0);
            //业绩提现
            case 'achievement':
                $amount = floor($amount * 100);
                $income = points_get_total($uid, 'achievement');
                if ($income >= $amount && $amount > 0) {
                    $t = variable_get_value('shushengyuan:achievement:service:charge');
                    $sa = floor($t * $amount);

                    $e = new ShusyCash();
                    $e->type = $type;
                    $e->uid = $uid;
                    $e->apply_amount = $amount;
                    $e->amount = $amount - $sa;
                    $e->service_amount = $sa;
                    $e->status = 0;
                    $e->info = '业绩提现';
                    $e->save();

                    points_to_uid($uid, '提现', 'achievement', -$amount);

                    return [
                        'code' => 0,
                        'msg' => 'ok',
                    ];
                }
                return [
                    'code' => 1,
                    'msg' => '金额不足',
                ];
            //店铺提现
            case 'store':
                $amount = floor($amount * 100);
                $income = points_get_total($uid, 'income');
                $store = $this->getStore();
                if ($income >= $amount && $amount > 0 && $store instanceof ShusyStore) {
                    //需要扣手续费
                    //$serviceCharge = variable_get_value('shushengyuan:cash:service:charge');
                    $serviceCharge = $store->charge;
                    $serviceAmount = floor($amount * $serviceCharge);

                    $e = new ShusyCash();
                    $e->type = $type;
                    $e->uid = $uid;
                    $e->apply_amount = $amount;
                    $e->amount = $amount - $serviceAmount;
                    $e->service_amount = $serviceAmount;
                    $e->status = 0;
                    $e->info = '店铺提现';
                    $e->save();

                    points_to_uid($uid, '提现', 'income', -$amount);

                    return [
                        'code' => 0,
                        'msg' => 'ok',
                    ];
                }
                return [
                    'code' => 1,
                    'msg' => '金额不足',
                ];
        }
        return [
            'code' => 2,
            'msg' => '提现类型不正确',
        ];
    }

    /**
     * @param int $sex
     * @param string $name
     * @param string $phone
     * @param string $identity
     * @param string $store_name
     * @return array
     * @OA\Post(
     *    path="/common/submit_store_taxation",
     *    summary="商家入驻 common/submit_store_taxation",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"sex","name","phone","identity""store_name"},
     *        @OA\Property(
     *          property="sex",
     *          type="integer",
     *          description="性别 1 男 2 女",
     *        ),
     *        @OA\Property(
     *          property="name",
     *          type="string",
     *          description="名字",
     *        ),
     *        @OA\Property(
     *          property="phone",
     *          type="string",
     *          description="联系电话",
     *        ),
     *        @OA\Property(
     *          property="identity",
     *          type="string",
     *          description="身份证号",
     *        )
     *        @OA\Property(
     *          property="store_name",
     *          type="string",
     *          description="店名",
     *        )
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_store_taxatio_list()
    {
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    function submit_store_taxation(
        string $name,
        string $store_name,
        string $ages,
        int $sex,
        string $phone,
        string $identity,
        string $store_title,
        string $doctor,
        string $remake,
        string $faith,
        string $nowdate
    )
    {
        $this->watchdog(__FUNCTION__, serialize(func_get_args()));
        $uid = $this->getUid();
        $es = shusy_taxation_load_multiple(FALSE, ['uid' => $uid]);
        $e = new ShusyTaxation();
        $e->uid = $uid;
        if ($e instanceof ShusyTaxation) {
            $e->name = $name;
            $e->sex = $sex;
            $e->phone = $phone;
            $e->identity = $identity;
            $e->store_name = $store_name;
            $e->ages = $ages;
            $e->store_name = $store_name;
            $e->store_title = $store_title;
            $e->remake = $remake;
            $e->doctor = $doctor;
            $e->faith = $faith;
            $e->nowdate = $nowdate;

            $e->status = 0;
            $e->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $sex
     * @param string $name
     * @param string $phone
     * @param string $identity
     * @param string $level_1
     * @param string $level_2
     * @param string $store_name
     * @param string $store_address
     * @param float $longitude
     * @param float $latitude
     * @param string $bank_no
     * @param string $bank_name
     * @param int $bank_face
     * @param int $identity_face
     * @param int $logo
     * @param int $business
     * @param string $open
     * @return array
     * @OA\Post(
     *    path="/common/submit_store_settle",
     *    summary="商家入驻 common/submit_store_settle",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"sex","name","phone","identity","level_1","level_2","store_name","store_address","longitude","latitude","bank_no","bank_name","bank_face","identity_face","logo","business","open"},
     *        @OA\Property(
     *          property="sex",
     *          type="integer",
     *          description="性别 1 男 2 女",
     *        ),
     *        @OA\Property(
     *          property="name",
     *          type="string",
     *          description="名字",
     *        ),
     *        @OA\Property(
     *          property="phone",
     *          type="string",
     *          description="联系电话",
     *        ),
     *        @OA\Property(
     *          property="identity",
     *          type="string",
     *          description="身份证号",
     *        ),
     *        @OA\Property(
     *          property="level_1",
     *          type="string",
     *          description="直推一级",
     *        ),
     *        @OA\Property(
     *          property="level_2",
     *          type="string",
     *          description="间推二级",
     *        ),
     *        @OA\Property(
     *          property="store_name",
     *          type="string",
     *          description="店名",
     *        ),
     *        @OA\Property(
     *          property="store_address",
     *          type="string",
     *          description="店铺地址",
     *        ),
     *        @OA\Property(
     *          property="longitude",
     *          type="string",
     *          description="经度",
     *        ),
     *        @OA\Property(
     *          property="latitude",
     *          type="string",
     *          description="纬度",
     *        ),
     *        @OA\Property(
     *          property="bank_no",
     *          type="string",
     *          description="收款卡号",
     *        ),
     *        @OA\Property(
     *          property="bank_name",
     *          type="string",
     *          description="开户行",
     *        ),
     *        @OA\Property(
     *          property="bank_face",
     *          type="integer",
     *          description="银行卡正面照 File.id",
     *        ),
     *        @OA\Property(
     *          property="identity_face",
     *          type="integer",
     *          description="身份证正面照 File.id",
     *        ),
     *        @OA\Property(
     *          property="logo",
     *          type="integer",
     *          description="店铺LOGO File.id",
     *        ),
     *        @OA\Property(
     *          property="business",
     *          type="integer",
     *          description="营业执照上传后的fid File.id",
     *        ),
     *        @OA\Property(
     *          property="open",
     *          type="string",
     *          description="营业时间",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_store_settle(int $sex, string $name, string $phone, string $identity, string $level_1, string $level_2, string $store_name, string $store_address, float $longitude, float $latitude, string $bank_no, string $bank_name, int $bank_face, int $identity_face, int $logo, int $business, string $open)
    {
        $this->watchdog(__FUNCTION__, serialize(func_get_args()));
        $uid = $this->getUid();
        $es = shusy_store_load_multiple(FALSE, ['uid' => $uid]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyStore();
            $e->uid = $uid;
        }
        if ($e instanceof ShusyStore) {
            if ($e->status == 1) {
                return [
                    'code' => 1,
                    'msg' => '已申请',
                ];
            }
            if (!empty($e->id) && $e->status == 0) {
                return [
                    'code' => 1,
                    'msg' => '审核中',
                ];
            }
            $e->sex = $sex;
            $e->name = $name;
            $e->phone = $phone;
            $e->identity = $identity;
            $e->level_1 = $level_1;
            $e->level_2 = $level_2;
            $e->store_name = $store_name;
            $e->store_address = $store_address;
            $e->coordinate = 3;
            $e->longitude = $longitude;
            $e->latitude = $latitude;
            $e->bank_no = $bank_no;
            $e->bank_name = $bank_name;
            $e->bank_file = $bank_face;
            $e->identity_face = $identity_face;
            $e->logo = $logo;
            $e->business = $business;
            $e->open = $open;
            $e->status = 0;
            $e->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param array $from
     * @return array
     * @OA\Post(
     *   path="/common/submitStoreSettle",
     *   summary="店家入驻 common/submitStoreSettle",
     *   tags={"v3.2",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"form",},
     *       @OA\Property(
     *         property="form",
     *         type="array",
     *         description="入驻参数",
     *         @OA\Items(type="string"),
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitStoreSettle(array $form)
    {
        try {
            //验证数据
            if (empty($form['sex'])) {
                throw new Exception('请填写性别.');
            }
            if (empty($form['birthday'])) {
                throw new Exception('请填写出生年月.');
            }
            if (empty($form['name'])) {
                throw new Exception('请填写名字.');
            }
            if (empty($form['phone'])) {
                throw new Exception('请填写联系电话.');
            }
            if (empty($form['identity'])) {
                throw new Exception('请填写身份证号.');
            }
            if (empty($form['level_1'])) {
                throw new Exception('请填写直推一级.');
            }
            if (empty($form['level_2'])) {
                throw new Exception('请填写间推二级.');
            }
            if (empty($form['store_name'])) {
                throw new Exception('请填写店名.');
            }
            if (empty($form['store_address'])) {
                throw new Exception('请填写店铺地址.');
            }
            if (empty($form['store_open'])) {
                throw new Exception('请填写营业时间.');
            }
            if (empty($form['bank_no'])) {
                throw new Exception('请填写收款卡号.');
            }
            if (empty($form['bank_name'])) {
                throw new Exception('请填写开户行.');
            }
            if (empty($form['imgs'][1][0]['fid'])) {
                throw new Exception('请填写身份证正面照.');
            }
            if (empty($form['imgs'][2][0]['fid'])) {
                throw new Exception('请填写银行卡正面照.');
            }
            if (empty($form['imgs'][3][0]['fid'])) {
                throw new Exception('请填写门店logo.');
            }
            if (empty($form['imgs'][4][0]['fid'])) {
                throw new Exception('请填写营业执照.');
            }
            $uid = $this->getUid();
            $es = shusy_store_load_multiple(FALSE, ['uid' => $uid]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new ShusyStore();
                $e->uid = $uid;
            }
            if ($e instanceof ShusyStore) {
                $fids = [];
                if ($e->status == 1) {
                    return [
                        'code' => 1,
                        'msg' => '已申请',
                    ];
                }
                if (!empty($e->id) && $e->status == 0) {
                    return [
                        'code' => 1,
                        'msg' => '审核中',
                    ];
                }
                //性别 0 未知 1 男 2 女
                switch ($form['sex']) {
                    case '男':
                        $e->sex = 1;
                        break;
                    case '女':
                        $e->sex = 2;
                        break;
                }
                $e->name = $form['name'];
                $e->phone = $form['phone'];
                $e->identity = $form['identity'];
                $e->level_1 = $form['level_1'];
                $e->level_2 = $form['level_2'];
                $e->store_name = $form['store_name'];
                $e->store_address = $form['store_address'];
                $e->open = $form['store_open'];

                $e->coordinate = 3;
                $e->longitude = $form['store_longitude'];
                $e->latitude = $form['store_latitude'];
                $e->bank_no = $form['bank_no'];
                $e->bank_name = $form['bank_name'];

                $e->identity_face = $form['imgs'][1][0]['fid'];
                $e->bank_file = $form['imgs'][2][0]['fid'];
                $e->logo = $form['imgs'][3][0]['fid'];
                $e->business = $form['imgs'][4][0]['fid'];

                if (!empty($form['imgs'][5][0]['fid'])) {
                    $fids[] = $form['imgs'][5][0]['fid'];
                }

                $e->status = 0;
                $e->save();
                if (!empty($fids)) {
                    $ew = $e->wrapper();
                    $dir = $this->filePrepareDirectory($e->entityType(), 'field_images', $e->bundle());
                    $imgs = [];
                    foreach ($fids as $fid) {
                        $file = file_load($fid);
                        $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
                        $rand = drupal_random_key(6);
                        $file = file_move($file, "{$dir}/{$uid}_{$fid}_{$rand}.{$ext}");
                        file_usage_add($file, 'shusy_store', 'field_images', $file->fid);
                        $imgs[] = ['fid' => $fid];
                    }
                    $ew->field_images->set($imgs);
                    $ew->save();
                }
            }
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        } catch (Exception $exception) {
            watchdog_exception(__FUNCTION__, $exception);
            return [
                'code' => 2,
                'msg' => $exception->getMessage(),
            ];
        }
    }

    /**
     * @param string $open
     * @return array
     * @OA\Post(
     *    path="/common/submit_change_store_open",
     *    summary="修改营业时间 common/submit_change_store_open",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        @OA\Property(
     *          property="open",
     *          type="string",
     *          description="营业时间",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_change_store_open(string $open)
    {
        $uid = $this->getUid();
        $es = shusy_store_load_multiple(FALSE, ['uid' => $uid]);
        if (!empty($es)) {
            $e = reset($es);
            if ($e instanceof ShusyStore) {
                $e->open = $open;
                $e->save();
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $sex
     * @param string $name
     * @param string $phone
     * @param string $bank_no
     * @param string $bank_name
     * @param string $address
     * @param string $reviewer
     * @param string $level_1
     * @param string $level_2
     * @param int $identity_face
     * @param int $bank_face
     * @return array
     * @OA\Post(
     *    path="/common/submit_distribution",
     *    summary="推广申请 common/submit_distribution",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"sex","name","phone","bank_no","bank_name","level_1","level_2","address","reviewer","identity_face","bank_face"},
     *        @OA\Property(
     *          property="sex",
     *          type="integer",
     *          description="性别 1 男 2 女",
     *        ),
     *        @OA\Property(
     *          property="name",
     *          type="string",
     *          description="名字",
     *        ),
     *        @OA\Property(
     *          property="phone",
     *          type="string",
     *          description="联系电话",
     *        ),
     *        @OA\Property(
     *          property="bank_no",
     *          type="string",
     *          description="收款卡号",
     *        ),
     *        @OA\Property(
     *          property="bank_name",
     *          type="string",
     *          description="开户行",
     *        ),
     *        @OA\Property(
     *          property="address",
     *          type="string",
     *          description="地址",
     *        ),
     *        @OA\Property(
     *          property="reviewer",
     *          type="string",
     *          description="审核人",
     *        ),
     *        @OA\Property(
     *          property="level_1",
     *          type="string",
     *          description="直推一级",
     *        ),
     *        @OA\Property(
     *          property="level_2",
     *          type="string",
     *          description="间推二级",
     *        ),
     *        @OA\Property(
     *          property="identity_face",
     *          type="integer",
     *          description="身份证正面照 File.id",
     *        ),
     *        @OA\Property(
     *          property="bank_face",
     *          type="integer",
     *          description="银行卡正面 File.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_distribution(int $sex, string $name, string $phone, string $bank_no, string $bank_name, string $address, string $reviewer, string $level_1, string $level_2, int $identity_face, int $bank_face)
    {
        $uid = $this->getUid();
        $es = shusy_distribution_load_multiple(FALSE, ['uid' => $uid]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyDistribution();
            $e->uid = $uid;
        }
        if ($e instanceof ShusyDistribution) {
            if ($e->status == 1) {
                return [
                    'code' => 1,
                    'msg' => '已申请',
                ];
            }
            if (!empty($e->id) && $e->status == 0) {
                return [
                    'code' => 1,
                    'msg' => '审核中',
                ];
            }
            $e->sex = $sex;
            $e->name = $name;
            $e->phone = $phone;
            $e->bank_no = $bank_no;
            $e->bank_name = $bank_name;
            $e->address = $address;
            $e->reviewer = $reviewer;
            $e->level_1 = $level_1;
            $e->level_2 = $level_2;
            $e->identity_face = $identity_face;
            $e->bank_face = $bank_face;
            $e->status = 0;
            $e->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param string $qr 二维码内容
     * @return array
     * 扫码登录PC后台
     * @OA\Post(
     *    path="/common/submit_pc_login",
     *    summary="商家扫码登录PC后台 common/submit_pc_login",
     *    tags={"v1.0"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        @OA\Property(
     *          property="qr",
     *          type="string",
     *          description="二维码内容",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_pc_login(string $qr)
    {
        $cid = 'pc_login_' . $qr;
        $cache = cache_get($cid, 'cache_shushengyuan');
        if (!empty($cache)) {
            if ($cache->expire >= REQUEST_TIME && $cache->data == 0) {
                $uid = $this->getUid();
                cache_set($cid, $uid, 'cache_shushengyuan', REQUEST_TIME + 30);
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
        }
        return [
            'code' => 1,
            'msg' => '登录失败',
        ];
    }

    /**
     * @param string $qr
     * @return array
     * @throws \ServicesException
     * @OA\Post(
     *    path="/common/submit_verification_service",
     *    summary="核销服务订单 common/submit_verification_service",
     *    tags={"v1.0","store"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"qr"},
     *        @OA\Property(
     *          property="qr",
     *          type="string",
     *          description="用户提供的服务核销二维码内容",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_verification_service(string $qr)
    {
        $cache = $this->cacheGet($qr);
        if (!empty($cache) && ($cache->expire >= REQUEST_TIME)) {
            $this->cacheClear($qr);
            $id = $cache->data;
            $store = $this->getStore();
            if ($store instanceof ShusyStore) {
                $service = shusy_service_load($id);
                if ($service instanceof ShusyService && $service->store_id == $store->id && $service->status == 0) {
                    $service->status = 1;
                    $service->save();
                    youji_income_order_line_unlock($service->store_order_id, $service->store_order_line_id, 1);
                    return [
                        'code' => 0,
                        'msg' => 'ok',
                    ];
                }
            }
        }
        return [
            'code' => 1,
            'msg' => '已核销',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submitRefundService",
     *    summary="服务订单申请退款 common/submitRefundService",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="MyServiceItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitRefundService(int $id)
    {
        $service = shusy_service_load($id);
        $uid = $this->getUid();
        if ($service instanceof ShusyService && $service->uid == $uid && $service->status == 0) {
            $service->status = 3;
            $service->save();
            //服务退款 需要处理推广订单 结算项 需要按数量拆
            //服务订单申请退款
            youji_income_order_line_refund_qty($service->store_order_id, $service->store_order_line_id, 1);
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submit_confirm_service",
     *    summary="用户确认服务订单核销 用户主动核销 无需商家确认 common/submit_confirm_service",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="MyServiceItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_confirm_service(int $id)
    {
        $service = shusy_service_load($id);
        $uid = $this->getUid();
        if ($service instanceof ShusyService && $service->uid == $uid && $service->status == 0) {
            $service->status = 1;
            $service->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submit_plant_grass_like",
     *    summary="种草点赞 common/submit_plant_grass_like",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="PlantGrassItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_plant_grass_like(int $id)
    {
        $uid = $this->getUid();
        $es = shusy_plant_grass_like_load_multiple(FALSE, [
            'uid' => $uid,
            'plant_grass_id' => $id,
        ]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyPlantGrassLike();
            $e->uid = $uid;
            $e->plant_grass_id = $id;
        }
        if ($e instanceof ShusyPlantGrassLike) {
            $e->status = 1;
            $e->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @param int $status
     * @return array
     * @OA\Post(
     *    path="/common/submit_favorite_product",
     *    summary="产品收藏/取消收藏 common/submit_favorite_product",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","status"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="ProductItem.id",
     *        ),
     *        @OA\Property(
     *          property="status",
     *          type="integer",
     *          description="是否收藏 0 否 1 是",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_favorite_product(int $id, int $status)
    {
        $uid = $this->getUid();
        $es = shusy_favorite_product_load_multiple(FALSE, [
            'product_id' => $id,
            'uid' => $uid,
        ]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyFavoriteProduct();
            $e->product_id = $id;
            $e->uid = $uid;
        }
        $e->status = $status;
        $e->save();

        if ($e->status == 1) {
            $ps = shusy_product_in_store_load_multiple(FALSE, ['product_id' => $id]);
            if (!empty($ps)) {
                $p = reset($ps);
                if ($p instanceof ShusyProductInStore) {
                    shusy_store_stats_record($id, 'follow');
                }
            }
        }

        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @OA\Post(
     *   path="/common/file_upload",
     *   summary="文件上传 common/file_upload",
     *   tags={"v1.0","file"},
     *   security={{"mini_token":{}},{"official_token":{}}},
     *   description="<a href='/api/upload-file.html'>点击查看上传文件示例</a>",
     *   @OA\RequestBody(
     *      required=true,
     *      @OA\MediaType(
     *             mediaType="multipart/form-data",
     *             @OA\Schema(
     *                 @OA\Property(
     *                     description="file to upload",
     *                     property="files[]",
     *                     type="string",
     *                     format="binary",
     *                 ),
     *                 required={"file"}
     *             )
     *         )
     * ),
     * @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="file",
     *         type="object",
     *         ref="#/components/schemas/File",
     *       ),
     *     )
     *   )
     * )
     */
    function file_upload()
    {
        //sites/all/modules/contrib/services/resources/file_resource.inc
        module_load_include('inc', 'services', 'resources/file_resource');
        if (!isset($_FILES['files']['name'])) {
            return [
                'code' => 1,
                'msg' => '未找到文件信息',
            ];
        }
        if (!is_array($_FILES['files']['name'])) {
            $_FILES['files']['name'] = [$_FILES['files']['name']];
            $_FILES['files']['type'] = [$_FILES['files']['type']];
            $_FILES['files']['tmp_name'] = [$_FILES['files']['tmp_name']];
            $_FILES['files']['error'] = [$_FILES['files']['error']];
            $_FILES['files']['size'] = [$_FILES['files']['size']];
        }
        foreach ($_FILES['files']['name'] as $field_name => $file_name) {
            $_FILES['files']['name'][$field_name] = _services_file_check_name_extension($file_name);
            $scheme = file_default_scheme();
            $validators = [];
            $extensions = variable_get('services_allowed_extensions', SERVICES_ALLOWED_EXTENSIONS);
            $validators['file_validate_extensions'] = [$extensions];
            $file = file_save_upload($field_name, $validators, "$scheme://");
            if (!empty($file->fid)) {
                $file->status = FILE_STATUS_PERMANENT;
                file_save($file);
                file_usage_add($file, 'services', 'files', $file->fid);

                $scheme = file_default_scheme();
                $ymd = format_date(REQUEST_TIME, 'custom', 'Y/m/d');
                $dir = "{$scheme}://tmp_services_files/{$ymd}";
                if (empty(file_prepare_directory($dir))) {
                    drupal_mkdir($dir, 0777, TRUE);
                }
                $file = file_move($file, "{$dir}/{$file->filename}");

                return [
                    'code' => 0,
                    'msg' => 'ok',
                    'file' => File::get($file->fid),
                ];
            }
        }
        return [
            'code' => 1,
            'msg' => '文件上传失败',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submit_point_exchange",
     *    summary="积分兑换 common/submit_point_exchange",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="PointProductItem.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="order",
     *         type="object",
     *         ref="#/components/schemas/PointExchangeOrder",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_point_exchange(int $id)
    {
        //检查积分是否足够
        $uid = $this->getUid();
        $point = points_get_total($uid, 'point');
        $product = shusy_point_product_load($id);
        if ($product instanceof ShusyPointProduct && $product->status == 1) {
            if ($point < $product->point) {
                return [
                    'code' => 2,
                    'msg' => '积分不足',
                ];
            }
            if ($product->stock() <= 0) {
                return [
                    'code' => 2,
                    'msg' => '库存不足',
                ];
            }
            //检查是否有未完成支付的订单
            $product->stockChange(-1);
            $order = new ShusyPointProductOrder();
            $order->uid = $uid;
            $order->point_product_id = $product->id;
            $order->point = $product->point;
            $order->status = 0;
            //需要支付的费用
            $order->amount = 0;
            $order->shipping_type = 'commerce_weight_shipping';
            //有效期 30 分钟
            $order->validity = REQUEST_TIME + (30 * 60);
            $order->save();
            return [
                'code' => 0,
                'msg' => 'ok',
                'order' => PointExchangeOrder::get($order->id),
            ];
        }
        return [
            'code' => 1,
            'msg' => '产品不存在或已下架',
        ];
    }

    /**
     * @param int $id
     * @param array $address
     * @return array
     * @OA\Post(
     *    path="/common/switch_point_exchange_order_address",
     *    summary="积分兑换切换收货地址 并计算运费 common/switch_point_exchange_order_address",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","address"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="PointExchangeOrder.id",
     *        ),
     *        @OA\Property(
     *          property="address",
     *          type="object",
     *          description="微信小程序返回的地址信息",
     *          ref="#/components/schemas/WxAddress"
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="order",
     *         type="object",
     *         ref="#/components/schemas/PointExchangeOrder"
     *       ),
     *     )
     *   )
     * )
     */
    function switch_point_exchange_order_address(int $id, array $address)
    {
        $uid = $this->getUid();
        $order = shusy_point_product_order_load($id);
        if ($order instanceof ShusyPointProductOrder && $order->uid == $uid) {
            $order->username = $address['userName'];
            $order->nationalcode = $address['nationalCode'];
            $order->telnumber = $address['telNumber'];
            $order->provincename = $address['provinceName'];
            $order->cityname = $address['cityName'];
            $order->countyname = $address['countyName'];
            $order->detailinfo = $address['detailInfo'];
            $order->postalcode = $address['postalCode'];
            //计算运费
            $shipping = variable_get_value('shushengyuan:shipping');
            $weightShipping = commerce_weight_shipping_load($shipping);
            if ($weightShipping instanceof CommerceWeightShipping) {
                $orderWrapper = $order->wrapper();
                $weight = $orderWrapper->product->weight->value();
                $amount = commerce_weight_shipping_callback_rate($weightShipping, ($weight / 1000), $order->nationalcode);
                $order->amount = $amount;
            }
            //切换地址刷新有效期
            $order->validity = REQUEST_TIME + (30 * 60);
            $order->save();
            return [
                'code' => 0,
                'msg' => 'ok',
                'order' => PointExchangeOrder::get($order->id),
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @throws \Exception
     * @OA\Post(
     *    path="/common/submit_point_exchange_order_pay",
     *    summary="支付兑换订单 common/submit_point_exchange_order_pay",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *   @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id",},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="PointExchangeOrder.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="unify",
     *         description="无需微信支付时返回 false",
     *         type="object",
     *         ref="#/components/schemas/WxPayUnify"
     *       ),
     *     )
     *   )
     * )
     */
    function submit_point_exchange_order_pay(int $id)
    {
        $uid = $this->getUid();
        $order = shusy_point_product_order_load($id);
        if ($order instanceof ShusyPointProductOrder && $order->uid == $uid && $order->status == 0) {
            //刷新有效期
            $order->validity = REQUEST_TIME + (30 * 60);
            $point = points_get_total($uid, 'point');
            if ($point >= $order->point) {
                //先扣积分
                points_to_uid($uid, t('积分兑换商品'), 'point', -$order->point);
                $order->status = 1;
                //存在运费 需要支付
                if ($order->amount > 0) {
                    $total_fee = $order->amount;
                    $wxController = new WxPayMiniPayController();
                    $unify = $wxController->orderUnifyAndBridgeConfig('shushengyuan', '积分兑换支付运费', $this->getOpenId(), $total_fee, ip_address(), "exchange|{$uid}|{$order->id}", WX_PAY_MINIPAY);
                    $order->save();
                    return [
                        'code' => 0,
                        'msg' => 'ok',
                        'unify' => $unify,
                    ];
                }
                $order->status = 2;
                $order->save();
                return [
                    'code' => 0,
                    'msg' => 'ok',
                    'unify' => FALSE,
                ];
            }
            return [
                'code' => 1,
                'msg' => '积分不足',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param int $id
     * @OA\Post(
     *    path="/common/submit_point_exchange_order_abandon",
     *    summary="放弃支付兑换订单运费 退回支付的积分 common/submit_point_exchange_order_abandon",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id",},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="PointExchangeOrder.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     * @return array
     */
    function submit_point_exchange_order_abandon(int $id)
    {
        $uid = $this->getUid();
        $order = shusy_point_product_order_load($id);
        if ($order instanceof ShusyPointProductOrder && $order->uid == $uid && ($order->status == 1 || $order->status == 0)) {
            $product = shusy_point_product_load($order->point_product_id);
            if ($product instanceof ShusyPointProduct) {
                $product->stockChange(1);
            }
            points_to_uid($uid, t('放弃支付兑换订单'), 'point', $order->point);
            $order->status = 3;
            $order->save();
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在.',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *    path="/common/submit_point_confirm_goods",
     *    summary="兑换订单确认收货 common/submit_point_confirm_goods",
     *    tags={"v1.0",},
     *    security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id",},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="PointExchangeOrder.id",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_point_confirm_goods(int $id)
    {
        $uid = $this->getUid();
        $order = shusy_point_product_order_load($id);
        if ($order instanceof ShusyPointProductOrder && $order->uid == $uid && ($order->status == 4 || $order->status == 2)) {
            $order->status = 5;
            $order->save();
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在.',
        ];
    }

    /**
     * @param int $id
     * @param int $lid
     * @param int $type
     * @param int $receipt
     * @param string $amount
     * @param int $reason
     * @param string $desc
     * @param array $fids
     * @return array
     * @throws \EntityMetadataWrapperException
     * @OA\Post(
     *    path="/common/submit_order_service",
     *    summary="提交售后申请 common/submit_order_service",
     *    tags={"v1.1",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","lid","type","receipt","amount","reason"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="订单ID OrderCart.id",
     *        ),
     *        @OA\Property(
     *          property="lid",
     *          type="integer",
     *          description="项ID LineItemProduct.id",
     *        ),
     *        @OA\Property(
     *          property="type",
     *          type="integer",
     *          description="申请类型 0 仅退款 1 退货退款",
     *        ),
     *        @OA\Property(
     *          property="receipt",
     *          type="integer",
     *          description="货物状态 0 未收到货 1 已收到货  退货退款时必为1"
     *        ),
     *        @OA\Property(
     *          property="amount",
     *          type="number",
     *          description="退款金额 已收到货时 可以编辑"
     *        ),
     *        @OA\Property(
     *          property="reason",
     *          type="integer",
     *          description="退款原因",
     *        ),
     *        @OA\Property(
     *          property="desc",
     *          type="string",
     *          description="退款说明",
     *        ),
     *        @OA\Property(
     *          property="fids",
     *          type="array",
     *          description="凭证FID",
     *          @OA\Items(type="integer")
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     * 提交售后申请
     */
    function submit_order_service(int $id, int $lid, int $type, int $receipt, string $amount, int $reason, string $desc, array $fids)
    {
        $order = shusy_store_order_load($id);
        $uid = $this->getUid();
        if ($order instanceof ShusyStoreOrder && $order->uid == $uid) {
            $sls = s_commerce_service_line_load_multiple(FALSE, ['line_item_id' => $lid]);
            if (!empty($sls)) {
                $sl = reset($sls);
            } else {
                $sl = new SCommerceServiceLine();
                $sl->line_item_id = $lid;
            }
            if ($sl instanceof SCommerceServiceLine) {
                //状态 0 待审核 1 待退款 2 已完成 3 拒绝 4 待退货
                switch ($sl->status) {
                    case 0:
                    case 1:
                    case 2:
                    case 4:
                        return [
                            'code' => 1,
                            'msg' => '售后处理中',
                        ];
                        break;
                }
                $sl->status = 0;
                $sl->save();
            }
            $sso = new SCommerceService();
            $sso->order_id = $id;
            $sso->line_item_id = $lid;
            $sso->type = $type;
            $sso->receipt = $receipt;
            $sso->amount = floor($amount * 100);
            $sso->reason = $reason;
            $sso->reason_desc = $desc;
            $sso->status = 0;
            $sso->store_id = $order->store_id;
            $ssoWrapper = $sso->wrapper();

            $imgs = [];
            $field_name = 'field_images';
            $dir = $this->filePrepareDirectory($sso->entityType(), $field_name, $sso->bundle());
            foreach ($fids as $fid) {
                $file = file_load($fid);
                $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
                $file = file_move($file, "{$dir}/{$this->getUid()}_{$fid}.{$ext}");
                file_usage_add($file, 's_commerce_service', $sso->entityType(), $file->fid);
                $imgs[] = ['fid' => $file->fid];
            }
            if (!empty($imgs)) {
                $ssoWrapper->field_images->set($imgs);
            }
            $ssoWrapper->save();

            //记录退单数据
            shusy_store_stats_record($order->store_id, 'refund');

            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param int $id 售后单ID
     * @param string $shipping_type 快递公司
     * @param string $shipping_number 快递单号
     * @param array $fids 凭证FID
     * @return array
     * 售后申请通过后 上传物流信息
     * @throws \EntityMetadataWrapperException
     * @OA\Post(
     *    path="/common/submit_order_service_shipping",
     *    summary="售后单上传物流信息 common/submit_order_service_shipping",
     *    tags={"v1.1",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","lid","shipping_type","shipping_number",},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="订单ID",
     *        ),
     *        @OA\Property(
     *          property="lid",
     *          type="integer",
     *          description="line.id",
     *        ),
     *        @OA\Property(
     *          property="shipping_type",
     *          type="string",
     *          description="快递公司",
     *        ),
     *        @OA\Property(
     *          property="shipping_number",
     *          type="string",
     *          description="快递单号",
     *        ),
     *        @OA\Property(
     *          property="fids",
     *          type="array",
     *          description="凭证FID",
     *          @OA\Items(type="integer")
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_order_service_shipping(int $id, int $lid, string $shipping_type, string $shipping_number, array $fids)
    {
        $uid = $this->getUid();
        $es = entity_load('s_commerce_service', FALSE, [
            'line_item_id' => $lid,
            'status' => 4,
        ]);
        if (!empty($es)) {
            $sso = reset($es);
            if ($sso instanceof SCommerceService && $sso->uid == $uid && $sso->status == 4) {
                $sso->status = 1;
                $sso->shipping_type = $shipping_type;
                $sso->shipping_number = $shipping_number;
                $ssoWrapper = $sso->wrapper();
                $imgs = [];
                $field_name = 'field_shipping_images';
                $dir = $this->filePrepareDirectory($sso->entityType(), $field_name, $sso->bundle());
                foreach ($fids as $fid) {
                    $file = file_load($fid);
                    $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
                    $file = file_move($file, "{$dir}/{$this->getUid()}_shipping_{$fid}.{$ext}");
                    file_usage_add($file, 's_commerce_service', $sso->entityType(), $file->fid);
                    $imgs[] = ['fid' => $file->fid];
                }
                $ssoWrapper->field_shipping_images->set($imgs);
                $ssoWrapper->save();

                $sls = s_commerce_service_line_load_multiple(FALSE, ['line_item_id' => $sso->line_item_id]);
                if (!empty($sls)) {
                    $sl = reset($sls);
                    if ($sl instanceof SCommerceServiceLine) {
                        //状态 0 待审核 1 待退款 2 已完成 3 拒绝 4 待退货
                        $sl->status = 1;
                        $sl->save();
                    }
                }
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
        }
        return [
            'code' => 1,
            'msg' => '售后单不存在',
        ];
    }


    /**
     * @param int $order_id
     * @param string $shipping_type
     * @param string $shipping_number
     * @return array
     * @throws \ServicesException
     * @OA\Post(
     *    path="/common/store_order_shipping",
     *    summary="订单发货 common/store_order_shipping",
     *    tags={"v1.1","vStore"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        @OA\Property(
     *          property="order_id",
     *          type="integer",
     *          description="订单ID"
     *        ),
     *        @OA\Property(
     *          property="shipping_type",
     *          type="string",
     *          description="快递公司",
     *        ),
     *        @OA\Property(
     *          property="shipping_number",
     *          type="string",
     *          description="快递单号",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     * 订单发货
     */
    function store_order_shipping(int $order_id, string $shipping_type, string $shipping_number)
    {
        $order = shusy_store_order_load($order_id);
        $store = $this->getStore();
        if ($order instanceof ShusyStoreOrder && $order->store_id == $store->id) {
            shusy_store_order_express($order, $shipping_type, $shipping_number);
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    /**
     * @param int $id 售后单ID
     * @param int $status 状态 0 审核 1 通过 2 拒绝
     * @param string $desc 说明
     * @return array
     * 审核售后单
     * @throws \ServicesException
     * @OA\Post(
     *    path="/common/store_submit_order_service_status",
     *    summary="审核售后单 common/store_submit_order_service_status",
     *    tags={"v1.1","vStore"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id","status"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="售后单ID",
     *        ),
     *        @OA\Property(
     *          property="status",
     *          type="integer",
     *          description="1 通过 2 拒绝",
     *        ),
     *        @OA\Property(
     *          property="desc",
     *          type="string",
     *          description="说明 如果拒绝的情况可以填写",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     * 审核售后单
     */
    function store_submit_order_service_status(int $id, int $status, string $desc)
    {
        $store = $this->getStore();
        $orderService = s_commerce_service_load($id);
        if ($orderService instanceof SCommerceService && $orderService->store_id == $store->id) {
            $es = entity_load('s_commerce_service_line', FALSE, [
                'line_item_id' => $orderService->line_item_id,
            ]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new SCommerceServiceLine();
                $e->line_item_id = $orderService->line_item_id;
            }
            if ($e instanceof SCommerceServiceLine) {
                //1 通过 2 拒绝
                switch ($status) {
                    case 1:
                        //状态 0 待审核 1 待退款 2 已完成 3 拒绝 4 待退货
                        //通过要判断是否是 退货退款
                        $orderService->status = 1;
                        $e->status = 1;
                        //申请类型 0 仅退款 1 退货退款
                        if ($orderService->type == 1) {
                            $orderService->status = 4;
                            $e->status = 4;
                        }
                        $e->save();
                        $orderService->save();
                        return [
                            'code' => 0,
                            'msg' => 'ok',
                        ];
                        break;
                    case 2:
                        $orderService->status = 3;
                        $e->status = 3;
                        $e->reason_desc = $desc;
                        $e->save();
                        $orderService->save();
                        return [
                            'code' => 0,
                            'msg' => 'ok',
                        ];
                        break;
                }
            }
            return [
                'code' => 1,
                'msg' => '选择正确的状态',
            ];
        }
        return [
            'code' => 1,
            'msg' => '售后单不存在',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @throws \ServicesException
     * @OA\Post(
     *    path="/common/store_submit_confirm_shipping",
     *    summary="售后单确认退货到货 common/store_submit_confirm_shipping",
     *    tags={"v1.1","vStore"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"id"},
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="售后单ID",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function store_submit_confirm_shipping(int $id)
    {
        $store = $this->getStore();
        $orderService = s_commerce_service_load($id);
        if ($orderService instanceof SCommerceService && $orderService->store_id == $store->id && $orderService->status == 4) {
            $es = entity_load('s_commerce_service_line', FALSE, [
                'line_item_id' => $orderService->line_item_id,
            ]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new SCommerceServiceLine();
                $e->line_item_id = $orderService->line_item_id;
            }
            if ($e instanceof SCommerceServiceLine && $e->status == 4) {
                //状态 0 待审核 1 待退款 2 已完成 3 拒绝 4 待退货
                $e->status = 1;
                $orderService->status = 1;
                $e->save();
                $orderService->save();
                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
        }
        return [
            'code' => 1,
            'msg' => '售后单不存在',
        ];
    }

    /**
     * @param int $id 售后单ID
     * @return array
     * 售后单退款
     * @throws \ServicesException
     * @OA\Post(
     *    path="/common/store_submit_order_refund",
     *    summary="售后单退款 common/store_submit_order_refund",
     *    tags={"v1.1","vStore"},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="售后单ID",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     * @deprecated
     * @todo 店铺自行同意售后单退款
     */
    function store_submit_order_refund(int $id)
    {
        $store = $this->getStore();
        $orderService = s_commerce_service_load($id);
        if ($orderService instanceof SCommerceService && $orderService->store_id == $store->id && $orderService->status == 1) {
            $orderService->status = 2;
            $orderService->save();
            $es = entity_load('s_commerce_service_line', FALSE, [
                'line_item_id' => $orderService->line_item_id,
            ]);
            if (!empty($es)) {
                $e = reset($es);
            } else {
                $e = new SCommerceServiceLine();
                $e->line_item_id = $orderService->line_item_id;
            }
            if ($e instanceof SCommerceServiceLine && $e->status == 1) {
                //状态 0 待审核 1 待退款 2 已完成 3 拒绝 4 待退货
                $e->status = 2;
                $e->save();

                //如果是最后一个 需要变更订单状态
                $ew = $e->wrapper();
                $commerce_line_items = $ew->line->order->lines;
                $order = $ew->line->order->value();
                $lastOne = TRUE;
                foreach ($commerce_line_items as $line_item) {
                    //需要检查是否是最后一个
                    if ($lastOne == TRUE) {
                        try {
                            if ($line_item->type->value() == 'product') {
                                //检查项售后状态 是否为最后一个
                                $line_item_id = $line_item->id->value();
                                $scses = s_commerce_service_line_load_multiple(FALSE, ['line_item_id' => $line_item_id]);
                                if (!empty($scses)) {
                                    $scse = reset($scses);
                                    //状态 0 待审核 1 待退款 2 已完成 3 拒绝 4 待退货
                                    if ($scse instanceof SCommerceServiceLine && $scse->status == 2) {
                                        //运行到此处说明这个项申请了售后
                                    } else {
                                        $lastOne = FALSE;
                                    }
                                } else {
                                    $lastOne = FALSE;
                                }
                            }
                        } catch (Exception $exception) {
                            watchdog_exception(__FUNCTION__ . __LINE__, $exception);
                        }
                    } else {
                        break;
                    }
                }
                if ($lastOne) {
                    if ($order instanceof ShusyStoreOrder) {
                        $order->status = 0;
                        $order->save();
                    }
                }

                //推荐订单 记录退款信息
                youji_income_order_line_refund($order->id, $e->line_item_id, $lastOne);
                //退款 处理店铺业绩信息
                $line = $ew->line->value();
                youji_profit_line_refund($order, $line, $orderService);
            }
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '售后单不存在',
        ];
    }

    /**
     * @return array
     * @OA\Post(
     *    path="/common/submit_draw_sweepstake",
     *    summary="抽奖 common/submit_draw_sweepstake",
     *    tags={"v1.0","sweepstake"},
     *    security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *       @OA\Property(
     *         property="index",
     *         type="integer",
     *         description="抽中的奖品下标",
     *       ),
     *       @OA\Property(
     *         property="type",
     *         type="integer",
     *         description="奖品类型 0 谢谢惠顾 1 积分 2 实物",
     *       ),
     *       @OA\Property(
     *         property="result",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submit_draw_sweepstake()
    {
        //抽奖次数控制
        $uid = $this->getUid();
        $ymd = $this->formatDate(REQUEST_TIME, 'Ymd');
        $logs = shusy_sweepstake_log_load_multiple(FALSE, [
            'in_day' => $ymd,
            'uid' => $uid,
        ]);
        if (!empty($logs)) {
            return [
                'code' => 1,
                'msg' => '每天只能抽一次',
            ];
        }
        $es = shusy_sweepstake_load_multiple(FALSE, ['status' => 1]);
        if (!empty($es)) {
            $e = reset($es);
            if ($e instanceof ShusySweepstake) {
                $list = [];
                $esItem = shusy_sweepstake_item_load_multiple(FALSE, [
                    'sweepstake_id' => $e->id,
                    'status' => 1,
                ]);
                $number = 0;
                foreach ($esItem as $eItem) {
                    if ($eItem instanceof ShusySweepstakeItem) {
                        $start = $number;
                        $end = $number + $eItem->number;
                        $list[] = [
                            'start' => $start,
                            'end' => $end,
                            'e' => $eItem,
                        ];
                        $number = $end;
                    }
                }
                $luck = mt_rand(0, $number);
                foreach ($list as $index => $item) {
                    if ($item['start'] <= $luck && $luck < $item['end']) {
                        $eItem = $item['e'];
                        if ($eItem instanceof ShusySweepstakeItem) {
                            $log = new ShusySweepstakeLog();
                            $log->uid = $uid;
                            $log->in_day = $ymd;
                            $log->sweepstake_id = $e->id;
                            $log->sweepstake_item_id = $eItem->id;
                            $log->save();
                            //奖品类型 0 谢谢惠顾 1 积分 2 实物
                            switch ($eItem->type) {
                                case 0:
                                    return [
                                        'code' => 0,
                                        'msg' => 'ok',
                                        'index' => (int)$index,
                                        'type' => (int)$eItem->type,
                                        'result' => '谢谢惠顾',
                                    ];
                                    break;
                                case 1:
                                    points_to_uid($uid, '抽奖', 'point', $eItem->point);
                                    return [
                                        'code' => 0,
                                        'msg' => 'ok',
                                        'index' => (int)$index,
                                        'type' => (int)$eItem->type,
                                        'result' => '积分已自动发放',
                                    ];
                                    break;
                                case 2:
                                    $order = new ShusyPointProductOrder();
                                    $order->uid = $uid;
                                    $order->point_product_id = $eItem->point_product_id;
                                    $order->point = 0;
                                    $order->status = 0;
                                    //需要支付的费用
                                    $order->amount = 0;
                                    $order->shipping_type = 'commerce_weight_shipping';
                                    //抽奖兑换商品 有效期 7 天
                                    $order->validity = REQUEST_TIME + (7 * 24 * 60 * 60);
                                    $order->save();

                                    //绑定抽奖记录关系
                                    $binds = shusy_sweepstake_bind_order_load_multiple(FALSE, [
                                        'sweepstake_log_id' => $log->id,
                                    ]);
                                    if (!empty($binds)) {
                                        $bind = reset($binds);
                                    } else {
                                        $bind = new ShusySweepstakeBindOrder();
                                        $bind->sweepstake_log_id = $log->id;
                                    }
                                    if ($bind instanceof ShusySweepstakeBindOrder) {
                                        $bind->point_product_order_id = $order->id;
                                        $bind->save();
                                    }

                                    return [
                                        'code' => 0,
                                        'msg' => 'ok',
                                        'index' => (int)$index,
                                        'type' => (int)$eItem->type,
                                        'result' => '已自动生成订单,请及时完成支付.',
                                    ];
                                    break;
                                case 3:
                                    $card = shusy_card_load($eItem->card_id);
                                    if ($card instanceof ShusyCard) {
                                        $cardWrapper = $card->wrapper();
                                        $clone = new ShusyGiftCard();
                                        $clone->name = $card->name;
                                        $clone->amount = $card->amount;
                                        $clone->status = 0;
                                        $clone->uid = $uid;
                                        $cloneWrapper = $clone->wrapper();
                                        $cloneWrapper->field_image->set($cardWrapper->field_image->value());
                                        $cloneWrapper->save();
                                        //绑定抽奖记录关系
                                        $binds = shusy_sweepstake_bind_card_load_multiple(FALSE, [
                                            'sweepstake_log_id' => $log->id,
                                        ]);
                                        if (!empty($binds)) {
                                            $bind = reset($binds);
                                        } else {
                                            $bind = new ShusySweepstakeBindCard();
                                            $bind->sweepstake_log_id = $log->id;
                                        }
                                        if ($bind instanceof ShusySweepstakeBindCard) {
                                            $bind->gift_card_id = $clone->id;
                                            $bind->save();
                                        }
                                        return [
                                            'code' => 0,
                                            'msg' => 'ok',
                                            'index' => (int)$index,
                                            'type' => (int)$eItem->type,
                                            'result' => '兑换券已自动发放',
                                        ];
                                    }
                                    break;
                            }
                        }
                    }
                }
            }
        }
        return [
            'code' => 1,
            'msg' => '没有配置抽奖活动',
        ];
    }


    /**
     * @param string $name
     * @param string $phone
     * @return array
     * @OA\Post(
     *    path="/common/submitTeamDistribution",
     *    summary="团队推广申请 common/submitTeamDistribution",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"name","phone",},
     *        @OA\Property(
     *          property="name",
     *          type="string",
     *          description="名字",
     *        ),
     *        @OA\Property(
     *          property="phone",
     *          type="string",
     *          description="电话",
     *        ),
     *      ),
     *    ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitTeamDistribution(string $name, string $phone)
    {
        $uid = $this->getUid();
        $es = shusy_team_apply_load_multiple(FALSE, ['uid' => $uid]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyTeamApply();
            $e->uid = $uid;
        }
        if ($e instanceof ShusyTeamApply) {
            if ($e->status == 1) {
                return [
                    'code' => 1,
                    'msg' => '已申请',
                ];
            }
            if (!empty($e->id) && $e->status == 0) {
                return [
                    'code' => 1,
                    'msg' => '审核中',
                ];
            }
            $e->name = $name;
            $e->phone = $phone;
            $e->status = 0;
            $e->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @return array
     * @OA\Post(
     *    path="/common/submitTeamCompanyLeaderApply",
     *    summary="申请市场部长 common/submitTeamCompanyLeaderApply",
     *    tags={"v1.0",},
     *    security={{"mini_token":{}},{"official_token":{}}},
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitTeamCompanyLeaderApply()
    {
        $uid = $this->getUid();
        $es = shusy_team_company_apply_load_multiple(FALSE, ['uid' => $uid]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyTeamCompanyApply();
            $e->uid = $uid;
        }
        if ($e instanceof ShusyTeamCompanyApply) {
            if ($e->status == 1) {
                return [
                    'code' => 1,
                    'msg' => '已申请',
                ];
            }
            if (!empty($e->id) && $e->status == 0) {
                return [
                    'code' => 1,
                    'msg' => '审核中',
                ];
            }
            $e->status = 0;
            $e->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param string $qr
     * @return array
     * @throws \ServicesException
     * @OA\Post(
     *    path="/common/submitGiftQr",
     *    summary="提交兑换二维码扫码后的内容 common/submitGiftQr",
     *    tags={"v1.0",},
     *    security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *    @OA\RequestBody(
     *      required=true,
     *      @OA\JsonContent(
     *        required={"qr",},
     *        @OA\Property(
     *          property="qr",
     *          type="string",
     *          description="二维码内容",
     *        ),
     *      ),
     *    ),
     *    @OA\Response(
     *      response=200, description="网络正常",
     *      @OA\JsonContent(
     *        @OA\Property(
     *          property="code",
     *          type="integer",
     *          description="返回码",
     *        ),
     *        @OA\Property(
     *          property="msg",
     *          type="string",
     *          description="返回信息",
     *        ),
     *     )
     *   )
     * )
     */
    function submitGiftQr(string $qr)
    {
        $store = $this->getStore();
        $cache = $this->cacheGet($qr);
        if (!empty($cache)) {
            [$id, $random] = explode('.', $qr);
            if ($cache->data == $id) {
                $this->cacheClear($qr);
                $gift = shusy_gift_card_load($id);
                if ($gift instanceof ShusyGiftCard && $gift->status == 0) {
                    $gift->store_id = $store->id;
                    $gift->status = 1;
                    $gift->save();
                    return [
                        'code' => 0,
                        'msg' => 'ok',
                    ];
                }
            }
        }
        return [
            'code' => 1,
            'msg' => '二维码无效',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *   path="/common/submitAgainBuyByOrder",
     *   summary="再次购买通过订单 common/submitAgainBuyByOrder",
     *   tags={"v2.2",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"id",},
     *       @OA\Property(
     *          property="id",
     *          type="integer",
     *          description="订单ID"
     *        ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitAgainBuyByOrder(int $id)
    {
        $uid = $this->getUid();
        $order = shusy_store_order_load($id);
        if ($order instanceof ShusyStoreOrder) {
            $storeOrderWrapper = $order->wrapper();
            $store = $storeOrderWrapper->store->value();
            if ($store instanceof ShusyStore) {
                $order = $this->createOrder($uid, $store->id);
                $lines = $storeOrderWrapper->lines;
                if ($lines instanceof EntityListWrapper) {
                    foreach ($lines->getIterator() as $line) {
                        //产品类型
                        if ($line->type->value() == 'product') {
                            $qty = $line->qty->value();
                            $standard = $line->standard->value();
                            if ($standard instanceof ShusyProductStandard && $standard->status == 1) {
                                $standardWrapper = $standard->wrapper();
                                if ($standardWrapper->stock->value() >= $qty) {
                                    $amountType = $line->amount_type->value();
                                    $amount = $standard->amount;
                                    $this->addCart($order, $standard, $amount, $qty, 0, $amountType, 0, 0);
                                    $cid = "payment_{$uid}";
                                    $this->cacheSet($cid, [$order->id]);
                                }
                            }
                        }
                    }
                }
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param string $name
     * @param string $phone
     * @return array
     * @OA\Post(
     *   path="/common/submitErrandApply",
     *   summary="提交快达申请 common/submitErrandApply",
     *   tags={"v1.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"name","phone"},
     *       @OA\Property(
     *         property="name",
     *         type="string",
     *         description="姓名",
     *       ),
     *       @OA\Property(
     *         property="phone",
     *         type="string",
     *         description="电话",
     *       ),
     *       @OA\Property(
     *         property="team",
     *         type="string",
     *         description="团队名",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitErrandApply(string $name, string $phone, string $team = "")
    {
        $uid = $this->getUid();
        $errands = shusy_errand_load_multiple(FALSE, ['uid' => $uid]);
        if (!empty($errands)) {
            $errand = reset($errands);
            if ($errand instanceof ShusyErrand) {
                //状态 0 未提交 1 已通过 2 审核中 3 未通过
                switch ($errand->status) {
                    case 0:
                    case 3:
                        $errand->name = $name;
                        $errand->phone = $phone;
                        $errand->team = $team;
                        $errand->status = 2;
                        $errand->save();
                        return [
                            'code' => 0,
                            'msg' => 'ok',
                        ];
                        break;
                }
                return [
                    'code' => 1,
                    'msg' => '已申请或审核中',
                ];
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @OA\Post(
     *   path="/common/submitOutErrandTeam",
     *   summary="踢出团队 common/submitOutErrandTeam",
     *   tags={"v1.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"id",},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="ID"
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitOutErrandTeam(int $id)
    {
        $uid = $this->getUid();
        $errand = shusy_errand_load($id);
        $inErrand = $this->getErrand();
        if ($errand instanceof ShusyErrand && $inErrand instanceof ShusyErrand && $errand->errand_id == $inErrand->id) {
            if ($errand->uid == $uid) {
                return [
                    'code' => 1,
                    'msg' => '不能踢自己',
                ];
            }
            $errand->status = 0;
            $errand->errand_id = 0;
            $errand->save();
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '非当前团队',
        ];
    }

    /**
     * @param int $id
     * @OA\Post(
     *   path="/common/submitDenyErrandTeam",
     *   summary="拒绝申请 common/submitDenyErrandTeam",
     *   tags={"v1.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"id",},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="ID"
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitDenyErrandTeam(int $id)
    {
        $uid = $this->getUid();
        $errand = shusy_errand_load($id);
        $inErrand = $this->getErrand();
        if ($errand instanceof ShusyErrand && $inErrand instanceof ShusyErrand && $errand->errand_id == $inErrand->id) {
            $errand->status = 3;
            $errand->save();
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '非当前团队',
        ];
    }

    /**
     * @param int $id
     * @OA\Post(
     *   path="/common/submitInErrandTeam",
     *   summary="通过申请 common/submitInErrandTeam",
     *   tags={"v1.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"id",},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="ID"
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitInErrandTeam(int $id)
    {
        $uid = $this->getUid();
        $inErrand = $this->getErrand();
        $errand = shusy_errand_load($id);
        if ($errand instanceof ShusyErrand && $inErrand instanceof ShusyErrand && $errand->errand_id == $inErrand->id) {
            $errand->status = 1;
            $errand->save();
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '非当前团队',
        ];
    }

    /**
     * @param string $name
     * @param string $phone
     * @return array
     * @OA\Post(
     *   path="/common/submitPromoteApply",
     *   summary="提交推广申请 common/submitPromoteApply",
     *   tags={"v1.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required={"name","phone"},
     *       @OA\Property(
     *         property="name",
     *         type="string",
     *         description="姓名",
     *       ),
     *       @OA\Property(
     *         property="phone",
     *         type="string",
     *         description="电话",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitPromoteApply(string $name, string $phone)
    {
        $uid = $this->getUid();
        $es = shusy_promote_load_multiple(FALSE, ['uid' => $uid]);
        if (!empty($es)) {
            $e = reset($es);
        } else {
            $e = new ShusyPromote();
            $e->uid = $uid;
        }
        if ($e instanceof ShusyPromote) {
            //状态 0 未申请 1 审核中 2 已通过 3 未通过
            switch ($e->status) {
                case 0:
                case 3:
                    $e->name = $name;
                    $e->phone = $phone;
                    $e->status = 1;
                    $e->uid = $this->getUid();
                    $e->save();
                    return [
                        'code' => 0,
                        'msg' => 'ok',
                    ];
            }
            return [
                'code' => 1,
                'msg' => '已申请或审核中',
            ];
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *   path="/common/submitPlantGrassComments",
     *   summary="提交种草推荐评论 common/submitPlantGrassComments",
     *   tags={"v3.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"id","content"},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="种草推荐ID",
     *       ),
     *       @OA\Property(
     *         property="content",
     *         type="string",
     *         description="评论内容",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitPlantGrassComments(int $id, string $content)
    {
        $result = $this->mini->content_security->checkText($content);
        if ($result['errcode'] != 0) {
            return [
                'code' => 1,
                'msg' => '评论内容含有违法违规内容',
            ];
        }
        $e = new ShusyPlantGrassComments();
        $e->plant_grass_id = $id;
        $e->content = $content;
        $e->status = 1;
        $e->save();
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $cid
     * @return array
     * @OA\Post(
     *   path="/common/submitDrawCoupon",
     *   summary="领取优惠券 common/submitDrawCoupon",
     *   tags={"v3.1",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"cid",},
     *       @OA\Property(
     *         property="cid",
     *         type="integer",
     *         description="优惠券ID",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitDrawCoupon(int $cid)
    {
        $uid = $this->getUid();
        $coupon = shusy_store_coupon_load($cid);
        if ($coupon instanceof ShusyStoreCoupon) {
            shusy_store_coupon_provide($uid, $coupon, '首页领取');
            return [
                'code' => 0,
                'msg' => 'ok',
            ];
        }
        return [
            'code' => 1,
            'msg' => '优惠券不存在',
        ];
    }

    /**
     * @return array
     * @OA\Post(
     *   path="/common/submitAddComment",
     *   summary="提交追加评论 common/submitAddComment",
     *   tags={"v1.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"id","content"},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="wx.login获取的code",
     *       ),
     *       @OA\Property(
     *         property="content",
     *         type="string",
     *         description="wx.login获取的code",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitAddComment(int $id, string $content)
    {
        $c = new ShusyProductComment();
        $c->product_id = $id;
        $c->score = 5;
        $c->has_img = 0;
        $c->content = $content;
        $c->status = 0;
        $c->is_add = 1;
        $c->save();
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $cid
     * @return array
     * @OA\Post(
     *   path="/common/submitDrawCouponfree",
     *   summary="领取优惠券 common/submitDrawCouponfree",
     *   tags={"v3.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"cid",},
     *       @OA\Property(
     *         property="cid",
     *         type="integer",
     *         description="优惠券ID",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitDrawCouponfree(int $cid)
    {
        $t = shusy_couponfree_log_load_multiple(FALSE, ['couponfree_id' => $cid]);
        if (empty($t)) {
            $uid = $this->getUid();
            $free = shusy_couponfree_load($cid);
            if ($free instanceof ShusyCouponfree && $free->status == 1) {
                $coupon = shusy_store_coupon_load($free->coupon_id);
                if ($coupon instanceof ShusyStoreCoupon) {
                    $t = new ShusyCouponfreeLog();
                    $t->uid = $uid;
                    $t->couponfree_id = $free->id;
                    $t->save();
                    shusy_store_coupon_provide($uid, $coupon, '自由领取');
                    return [
                        'code' => 0,
                        'msg' => 'ok',
                    ];
                }
            }
            return [
                'code' => 1,
                'msg' => '手慢无',
            ];
        }
        return [
            'code' => 1,
            'msg' => '已领取',
        ];
    }

    /**
     * @param int $id
     * @param int $gold
     * @return array
     * @OA\Post(
     *   path="/common/submitGold",
     *   summary="金币抵扣 common/submitGold",
     *   tags={"v3.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"id","gold"},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="订单号",
     *       ),
     *       @OA\Property(
     *         property="gold",
     *         type="string",
     *         description="抵扣金额",
     *       ),
     *     ),
     *   ),
     * @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitGold(int $id, string $gold)
    {
        $gold = floor($gold * 100);
        $order = shusy_store_order_load($id);
        if ($order instanceof ShusyStoreOrder) {
            $max = $this->getMaxGold($order);
            if ($gold > $max) {
                return [
                    'code' => 1,
                    'msg' => '超过最大抵扣金额',
                ];
            }
            $total = points_get_total($order->uid, 'gold');
            if ($total >= $gold) {
                $amount = $gold;
                $lines = shusy_store_order_line_load_multiple(FALSE, [
                    'store_order_id' => $order->id,
                    'type' => 'gold',
                ]);
                if (!empty($lines)) {
                    $line = reset($lines);
                } else {
                    $line = new ShusyStoreOrderLine();
                    $line->store_order_id = $order->id;
                    $line->type = 'gold';
                }
                $line->status = 1;
                $line->name = '金币抵扣';
                $line->qty = 1;
                $line->amount = -$amount;
                $line->total = $line->qty * $line->amount;
                $line->payment = 1;
                $line->save();

                $t = shusy_store_order_gold_new_single(FALSE, ['store_order_line_id' => $line->id]);
                $t->store_order_line_id = $line->id;
                $t->gold = $gold;
                $t->save();

                $order->save();

                return [
                    'code' => 0,
                    'msg' => 'ok',
                ];
            }
            return [
                'code' => 1,
                'msg' => '金币不足',
            ];
        }
        return [
            'code' => 1,
            'msg' => '订单不存在',
        ];
    }

    protected function getMaxGold(ShusyStoreOrder $order)
    {
        $max = 0;
        $products = $order->products();
        foreach ($products as $line) {
            if ($line instanceof ShusyStoreOrderLine) {
                $lineWrapper = $line->wrapper();
                $gold = $lineWrapper->standard->gold->value();
                if ($gold) {
                    $max += $line->total;
                }
            }
        }
        return $max;
    }

    /**
     * @param int $id
     * @return array
     * @OA\Post(
     *   path="/common/submitHotelRoomSchedule",
     *   summary="酒店预定 common/submitHotelRoomSchedule",
     *   tags={"v3.2",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"id",},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="room.id",
     *       ),
     *       @OA\Property(
     *         property="qty",
     *         type="integer",
     *         description="预定数量",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitHotelRoomSchedule(int $id, int $qty)
    {
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @param string $ymd
     * @return array
     * @OA\Post(
     *   path="/common/submitHotelRoomScheduleDay",
     *   summary="预订日历 common/submitHotelRoomScheduleDay",
     *   tags={"v3.2",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"id","ymd",},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="room.id",
     *       ),
     *       @OA\Property(
     *         property="ymd",
     *         type="string",
     *         description="日期",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitHotelRoomScheduleDay(int $id, string $ymd)
    {
        $uid = $this->getUid();
        $room = shusy_hotel_room_load($id);
        if ($room instanceof ShusyHotelRoom) {
            $hotel = shusy_hotel_load($room->hotel_id);
            $order = $this->getHotelOrder($hotel, $uid);
            $occupancy = strtotime($ymd);
            $line = new ShusyHotelLine();
            $line->order_id = $order->id;
            $line->name = $room->name;
            $line->amount = $room->amount;
            $line->qty = 1;
            $line->total = $line->amount * $line->qty;
            $line->status = 1;
            $line->save();
            $lineRoom = new ShusyHotelLineRoom();
            $lineRoom->line_id = $line->id;
            $lineRoom->room_id = $room->id;
            $lineRoom->occupancy = $occupancy;
            $lineRoom->save();
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @param int $id
     * @param string $ymd
     * @return array
     * @OA\Post(
     *   path="/common/submitSwitchHotelRoomScheduleDay",
     *   summary="切换预订选择 common/submitSwitchHotelRoomScheduleDay",
     *   tags={"v3.2",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"id","ymd",},
     *       @OA\Property(
     *         property="id",
     *         type="integer",
     *         description="room.id",
     *       ),
     *       @OA\Property(
     *         property="ymd",
     *         type="string",
     *         description="日期",
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitSwitchHotelRoomScheduleDay(int $id, string $ymd)
    {
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    protected function getHotelOrder(ShusyHotel $hotel, int $uid)
    {
        $order = shusy_hotel_order_new_single(FALSE, [
            'uid' => $uid,
            'hotel_id' => $hotel->id,
            'status' => 1,
        ]);
        if (empty($order->id)) {
            $order->save();
        }
        return $order;
    }

    /**
     * @param array $options
     * @return array
     * @OA\Post(
     *   path="/common/submitAppShowOptions",
     *   summary="提交app onshow 的参数 common/submitAppShowOptions",
     *   tags={"v3.2",},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"options",},
     *       @OA\Property(
     *         property="options",
     *         type="array",
     *         description="参数",
     *         @OA\Items(type="string"),
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitAppShowOptions(array $options)
    {
        watchdog(__FUNCTION__, serialize($options));
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

    /**
     * @return array
     * @OA\Post(
     *   path="/common/submitIntentionStore",
     *   summary="提交意向资料 common/submitIntentionStore",
     *   tags={"v1.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"form",},
     *       @OA\Property(
     *         property="form",
     *         type="array",
     *         description="提交的资料",
     *         @OA\Items(type="string"),
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitIntentionStore(array $form)
    {
        if (empty($form['phone'])) {
            return [
                'code' => 2,
                'msg' => '请填写联系方式',
            ];
        }
        $e = new Ssystore($form);
        $e->save();
        return [
            'code' => 0,
            'msg' => '提交成功',
        ];
    }

    /**
     * @param array $res
     * @return array
     * @OA\Post(
     *   path="/common/submitSubscribeMessage",
     *   summary="提交订阅消息成功记录 common/submitSubscribeMessage",
     *   tags={"v2.0",},
     *   security={{"token":{}},{"mini_token":{}},{"official_token":{}},{"app_token":{}}},
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       required ={"res",},
     *       @OA\Property(
     *         property="res",
     *         type="array",
     *         description="requestSubscribeMessage success res",
     *         @OA\Items(type="integer"),
     *       ),
     *     ),
     *   ),
     *   @OA\Response(
     *     response=200, description="网络正常",
     *     @OA\JsonContent(
     *       @OA\Property(
     *         property="code",
     *         type="integer",
     *         description="返回码",
     *       ),
     *       @OA\Property(
     *         property="msg",
     *         type="string",
     *         description="返回信息",
     *       ),
     *     )
     *   )
     * )
     */
    function submitSubscribeMessage(array $res)
    {
        $uid = $this->getUid();
        if (module_exists('swx_submsgs')) {
            foreach ($res as $id => $status) {
                if ($id != 'errMsg') {
                    $e = new SwxSubmsgs();
                    $e->uid = $uid;
                    $e->tmplid = $id;
                    /**
                     * 'accept'表示用户同意订阅该条id对应的模板消息，
                     * 'reject'表示用户拒绝订阅该条id对应的模板消息，
                     * 'ban'表示已被后台封禁，
                     * 'filter'表示该模板因为模板标题同名被后台过滤
                     */
                    $e->status = 0;
                    switch ($status) {
                        case 'accept':
                            $e->status = 0;
                            $e->save();
                            break;
                    }
                }
            }
        }
        return [
            'code' => 0,
            'msg' => 'ok',
        ];
    }

}
